package com.dzl.goods.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.dzl.admin.pojo.vo.LoginSysAdminVo;
import com.dzl.aliyunoss.ALiYunOSSConstant;
import com.dzl.base.service.BaseServiceImpl;
import com.dzl.brand.pojo.WelfareBrand;
import com.dzl.config.database.Master;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.*;
import com.dzl.goods.dao.WelfareGoodsMapper;
import com.dzl.goods.pojo.*;
import com.dzl.goods.pojo.dto.WelfareGoodsAttrCostPriceDto;
import com.dzl.goods.pojo.dto.WelfareGoodsBatchUpdateDto;
import com.dzl.goods.pojo.dto.WelfareGoodsManageAddDto;
import com.dzl.goods.pojo.query.WelfareGoodsAttrQuery;
import com.dzl.goods.pojo.query.WelfareGoodsDevAreaQuery;
import com.dzl.goods.pojo.query.WelfareGoodsManageQuery;
import com.dzl.goods.pojo.query.WelfareGoodsPageQuery;
import com.dzl.goods.pojo.vo.*;
import com.dzl.goods.service.*;
import com.dzl.middleground.pojo.query.SearchGoodsQuery;
import com.dzl.middleground.pojo.vo.SearchGoodsListVo;
import com.dzl.moive.pojo.WelfareMovieInfo;
import com.dzl.operation.service.OperationLogService;
import com.dzl.supplier.pojo.WelfareSupplier;
import com.dzl.supplier.pojo.vo.WelfareSupplierVo;
import com.dzl.supplier.service.WelfareSupplierBrandService;
import com.dzl.supplier.service.WelfareSupplierService;
import com.dzl.util.EmptyUtils;
import com.dzl.util.ImageUtils;
import com.dzl.voucherSecretGroup.pojo.vo.VoucherSecretGroupSellVo;
import com.dzl.voucherSecretGroup.service.WelfareVoucherSecretGroupService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * 商品表(WelfareGoods)表服务实现类
 *
 * @author ChenLong
 * @since 2021-05-18 10:01:45
 */
@Service("welfareGoodsService")
public class WelfareGoodsServiceImpl extends BaseServiceImpl<WelfareGoods> implements WelfareGoodsService {

    @Autowired
    private WelfareGoodsMapper welfareGoodsMapper;
    @Autowired
    private WelfareGoodsImgService welfareGoodsImgService;
    @Autowired
    private WelfareSupplierService welfareSupplierService;
    @Autowired
    private WelfareGoodsAttrService welfareGoodsAttrService;
    @Autowired
    private WelfareGoodsAttrGroupService welfareGoodsAttrGroupService;
    @Autowired
    private WelfareGoodsAttrDetailService welfareGoodsAttrDetailService;
    @Autowired
    private WelfareGoodsAttrGroupRelService welfareGoodsAttrGroupRelService;
    @Autowired
    private WelfareVoucherSecretGroupService welfareVoucherSecretGroupService;
    @Autowired
    private WelfareGoodsLabelRelService welfareGoodsLabelRelService;
    @Autowired
    private WelfareGoodsLabelService welfareGoodsLabelService;
    @Autowired
    private WelfareGoodsCategoryRelService welfareGoodsCategoryRelService;
    @Autowired
    private WelfareGoodsModifyRecordService welfareGoodsModifyRecordService;
    @Autowired
    private WelfareGoodsSupplierService welfareGoodsSupplierService;
    @Autowired
    private WelfareSupplierBrandService welfareSupplierBrandService;
    @Autowired
    private OperationLogService operationLogService;


    private final Integer GOODS_BUY_LIMIT = 9999;

    @Override
    public PageInfo<WelfareJicaiGoodsManageVo> getWelfareJicaiGoodsListPage(WelfareGoodsManageQuery query) {
        PageHelper.startPage(query);
        List<WelfareJicaiGoodsManageVo> list = welfareGoodsMapper.selectJicaiGoodsList(query);
        list.forEach(goodsVo->{
            goodsVo.setGoodsImg(ImageUtils.setImageSrc(goodsVo.getGoodsImg()));
            //当isChecked和categoryId为空表示查集采商品列表，则需要查商品关联品类和供应商
            if(query.getIsChecked() == null && query.getCategoryId() == null){
                //查品类
                List<WelfareGoodsCategoryRel> goodsCategoryRelList = welfareGoodsCategoryRelService.selectGoodsCategoryRelByGoodsId(goodsVo.getId());
                if (EmptyUtils.isNotEmpty(goodsCategoryRelList)) {
                    StringBuffer sb = new StringBuffer();
                    goodsCategoryRelList.forEach(x->{
                        sb.append(x.getCategoryName()).append(",");
                    });
                    goodsVo.setCategoryName(sb.substring(0,sb.length()-1));
                }
                //查供应商
                List<WelfareGoodsSupplier> goodsSupplierList = welfareGoodsSupplierService.selectGoodsSupplierByGoodsId(goodsVo.getId());
                if (EmptyUtils.isNotEmpty(goodsSupplierList)) {
                    goodsVo.setGoodsSupplierList(goodsSupplierList);
                }
            }
        });
        PageInfo<WelfareJicaiGoodsManageVo> page = new PageInfo<WelfareJicaiGoodsManageVo>(list);
        return page;
    }

    @Override
    public PageInfo<WelfareGoodsManageVo> getWelfareGoodsListPage(WelfareGoodsManageQuery query) {
        PageHelper.startPage(query);
        List<WelfareGoodsManageVo> welfareGoodsManageVoList = welfareGoodsMapper.getGoodsListManage(query);
        if (EmptyUtils.isNotEmpty(welfareGoodsManageVoList)) {
            welfareGoodsManageVoList.forEach(welfareGoodsManageVo -> {
                if (EmptyUtils.isNotEmpty(welfareGoodsManageVo.getGoodsImg())) {
                    welfareGoodsManageVo.setGoodsImg(ImageUtils.setImageSrc(welfareGoodsManageVo.getGoodsImg()));
                }
                if (EmptyUtils.isNotEmpty(welfareGoodsManageVo.getGoodsType())) {
                    // 商品类型
                    if (welfareGoodsManageVo.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_PHYSICAL.getCode())) {
                        welfareGoodsManageVo.setGoodsTypeName(WelfareGoodsEnum.GOODS_TYPE_PHYSICAL.getName());
                    } else if (welfareGoodsManageVo.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getCode())) {
                        welfareGoodsManageVo.setGoodsTypeName(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getName());
                    }
                }
                if (welfareGoodsManageVo.getGoodsStatus().equals(WelfareGoodsEnum.GOODS_STATUS_TYPE_DOWN.getCode())) {
                    welfareGoodsManageVo.setGoodsStatusName(WelfareGoodsEnum.GOODS_STATUS_TYPE_DOWN.getName());
                } else if (welfareGoodsManageVo.getGoodsStatus().equals(WelfareGoodsEnum.GOODS_STATUS_TYPE_DRAFT.getCode())) {
                    welfareGoodsManageVo.setGoodsStatusName(WelfareGoodsEnum.GOODS_STATUS_TYPE_DRAFT.getName());
                } else if (welfareGoodsManageVo.getGoodsStatus().equals(WelfareGoodsEnum.GOODS_STATUS_TYPE_SHELVES.getCode())) {
                    welfareGoodsManageVo.setGoodsStatusName(WelfareGoodsEnum.GOODS_STATUS_TYPE_SHELVES.getName());
                } else if (welfareGoodsManageVo.getGoodsStatus().equals(WelfareGoodsEnum.GOODS_STATUS_TYPE_DOWN_PLATFORM.getCode())) {
                    welfareGoodsManageVo.setGoodsStatusName(WelfareGoodsEnum.GOODS_STATUS_TYPE_DOWN_PLATFORM.getName());
                    welfareGoodsManageVo.setGoodsStatus(WelfareGoodsEnum.GOODS_STATUS_TYPE_DOWN.getCode());
                }

                if(EmptyUtils.isNotEmpty(welfareGoodsManageVo.getPlatformId())){
                    welfareGoodsManageVo.setEnterpriseGoodsSource(CommonConstants.APP_GOODS_SOURCE.PLAFORM);
                }else{
                    welfareGoodsManageVo.setEnterpriseGoodsSource(CommonConstants.APP_GOODS_SOURCE.SELF);
                }
                //设置id复选框的值，用于商品批量操作时候的校验
                StringBuffer idCheckBoxValueSB = new StringBuffer();
                idCheckBoxValueSB.append(welfareGoodsManageVo.getId()).append("_").append(welfareGoodsManageVo.getPlatformId()==null?0:welfareGoodsManageVo.getPlatformId()).append("_")
                        .append(welfareGoodsManageVo.getGoodsStatus()).append("_").append(welfareGoodsManageVo.getGoodsType());
                welfareGoodsManageVo.setIdCheckBoxValue(idCheckBoxValueSB.toString());

                welfareGoodsManageVo.setIsShowName(welfareGoodsManageVo.getIsShow() != 1);
                //查询商品最低价最高价等
                WelfareGoodsManageVo goodsPriceVo = welfareGoodsMapper.selectGoodsPriceAndQuantityByGoodsId(welfareGoodsManageVo.getId());
                if (EmptyUtils.isNotEmpty(goodsPriceVo)) {
                    welfareGoodsManageVo.setLowerPrice(goodsPriceVo.getLowerPrice());
                    welfareGoodsManageVo.setUpperPrice(goodsPriceVo.getUpperPrice());
                    welfareGoodsManageVo.setLowerCostPrice(goodsPriceVo.getLowerCostPrice());
                    welfareGoodsManageVo.setUpperCostPrice(goodsPriceVo.getUpperCostPrice());
                    welfareGoodsManageVo.setLowerProfit(goodsPriceVo.getLowerProfit());
                    welfareGoodsManageVo.setUpperProfit(goodsPriceVo.getUpperProfit());
                    welfareGoodsManageVo.setGoodsRemainQuantity(goodsPriceVo.getGoodsRemainQuantity());
                    welfareGoodsManageVo.setGoodsLockQuantity(goodsPriceVo.getGoodsLockQuantity());
                    welfareGoodsManageVo.setLowerProfit(EmptyUtils.isEmpty(welfareGoodsManageVo.getLowerProfit()) ? BigDecimal.ZERO : welfareGoodsManageVo.getLowerProfit().setScale(2, BigDecimal.ROUND_HALF_UP));
                    welfareGoodsManageVo.setUpperProfit(EmptyUtils.isEmpty(welfareGoodsManageVo.getUpperProfit()) ? BigDecimal.ZERO : welfareGoodsManageVo.getUpperProfit().setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                //如果是平台端查询,则商品销售数量需要加上该商品在其他的企业端小程序上销售数量
                if(query.getEnterpriseId()==CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_ID){
                    Integer num = welfareGoodsMapper.selectPlatformGoodsConvertQuantityByGoodsId(welfareGoodsManageVo.getPlatformId());
                    welfareGoodsManageVo.setGoodsConvertQuantity(welfareGoodsManageVo.getGoodsConvertQuantity()+num);
                }else{
                    //如果是企业端查,则利润率和库存数量和分区名称默认都显示"-"，且供应商名称显示为"福力兔"
                    if(EmptyUtils.isNotEmpty(welfareGoodsManageVo.getPlatformId()) && welfareGoodsManageVo.getPlatformId()>0){
                        welfareGoodsManageVo.setSupplierName(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_NAME);
                        //x.setProfit("-");
                        welfareGoodsManageVo.setLowerProfit(new BigDecimal(0));
                        welfareGoodsManageVo.setUpperProfit(new BigDecimal(0));
                        welfareGoodsManageVo.setGoodsRemainQuantity(null);
                        welfareGoodsManageVo.setPartitionName("-");
                    }
                }
            });
        }
        PageInfo<WelfareGoodsManageVo> page = new PageInfo<WelfareGoodsManageVo>(welfareGoodsManageVoList);
        return page;
    }

    @Override
    public PageInfo<WelfareSkuGoodsVo> getWelfareGoodsAttrListPage(WelfareGoodsAttrQuery query) {
        PageHelper.startPage(query);
        List<WelfareSkuGoodsVo> list = welfareGoodsMapper.selectGoodsAttrListManage(query);
        list.forEach(x->{
            if(EmptyUtils.isNotEmpty(x.getSkuPic())){
                x.setGoodsImg(ImageUtils.setImageSrc(x.getSkuPic()));
            }else if(EmptyUtils.isNotEmpty(x.getGoodsImg())){
                x.setGoodsImg(ImageUtils.setImageSrc(x.getGoodsImg()));
            }else{
                x.setGoodsImg("");
            }
            x.setSkuId(x.getId());
            StringBuffer goodsAttr = new StringBuffer();
            goodsAttr.append(x.getFirstDetailName());
            if(EmptyUtils.isNotEmpty(x.getSecondDetailName())){
                goodsAttr.append("/").append(x.getSecondDetailName());
            }
            BigDecimal profit = (x.getPrice().subtract(x.getCostPrice())).multiply(new BigDecimal(100)).divide(x.getPrice(),4, RoundingMode.HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
            x.setProfit(profit);
            if(EmptyUtils.isNotEmpty(x.getThirdDetailName())){
                goodsAttr.append("/").append(x.getThirdDetailName());
            }
            x.setGoodsAttr(goodsAttr.toString());
            if(x.getGoodsType()==WelfareGoodsEnum.GOODS_TYPE_PHYSICAL.getCode()){
                x.setGoodsTypeName(WelfareGoodsEnum.GOODS_TYPE_PHYSICAL.getName());
            }else{
                x.setGoodsTypeName(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getName());
            }
            x.setDisplayPrice(x.getPrice());
            if(x.getGoodsStatus()== WelfareGoodsEnum.GOODS_STATUS_TYPE_SHELVES.getCode()){
                if(x.getIsShow()==CommonConstants.YES){
                    x.setGoodsStatusName("上架/不隐藏");
                }else{
                    x.setGoodsStatusName("上架/已隐藏");
                }
            }else{
                x.setGoodsStatusName("下架");
            }
        });
        PageInfo<WelfareSkuGoodsVo> page = new PageInfo<WelfareSkuGoodsVo>(list);
        return page;
    }

    @Override
    public WelfareGoodsDetailVo getGoodsInfoDetail(Integer goodsId) {
        WelfareGoodsDetailVo welfareGoodsDetailVo = welfareGoodsMapper.selectGoodsInfoDetailById(goodsId);
        if (EmptyUtils.isNotEmpty(welfareGoodsDetailVo.getGoodsType())) {
            // 商品类型
            if (welfareGoodsDetailVo.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_PHYSICAL.getCode())) {
                welfareGoodsDetailVo.setGoodsTypeName(WelfareGoodsEnum.GOODS_TYPE_PHYSICAL.getName());
            } else if (welfareGoodsDetailVo.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getCode())) {
                welfareGoodsDetailVo.setGoodsTypeName(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getName());
            }
            if (EmptyUtils.isEmpty(welfareGoodsDetailVo.getGoodsGroupList())) {
                // 处理为空json数组
                welfareGoodsDetailVo.setGoodsGroupList(new JSONArray().toString());
            }
            if (EmptyUtils.isNotEmpty(welfareGoodsDetailVo.getBuyLimit()) && welfareGoodsDetailVo.getBuyLimit().equals(GOODS_BUY_LIMIT)) {
                welfareGoodsDetailVo.setBuyLimit(0);
            }
        }
        welfareGoodsDetailVo.setGoodsImg(ImageUtils.setImageSrc(welfareGoodsDetailVo.getGoodsImg()));
        WelfareGoodsImg welfareGoodsImg = new WelfareGoodsImg();
        welfareGoodsImg.setGoodsId(goodsId);
        welfareGoodsImg.setStatus(1);
        List<WelfareGoodsImg> welfareGoodsImgList = welfareGoodsImgService.select(welfareGoodsImg);
        //如果图片为空，则有可能是创建企业同步商品时候创建的商品，需要第一次加载详情时候同步商品图片
        if(EmptyUtils.isEmpty(welfareGoodsImgList) && EmptyUtils.isNotEmpty(welfareGoodsDetailVo.getPlatformId())){
            welfareGoodsImg.setGoodsId(welfareGoodsDetailVo.getPlatformId());
            welfareGoodsImgList = welfareGoodsImgService.select(welfareGoodsImg);
            if (EmptyUtils.isNotEmpty(welfareGoodsImgList)) {
                welfareGoodsImgList.forEach(welfareGoodsImg1 -> {
                    welfareGoodsImg1.setGoodsId(goodsId);
                    welfareGoodsImg1.setEnterpriseId(welfareGoodsDetailVo.getEnterpriseId());
                    welfareGoodsImg1.setId(null);
                });
                welfareGoodsImgService.insertList(welfareGoodsImgList);
            }
        }
        if (EmptyUtils.isNotEmpty(welfareGoodsImgList)) {
            welfareGoodsImgList.forEach(welfareGoodsImg1 -> {
                if (EmptyUtils.isNotEmpty(welfareGoodsImg1.getImg())) {
                    welfareGoodsImg1.setImg(ImageUtils.setImageSrc(welfareGoodsImg1.getImg()));
                }
            });
        }
        welfareGoodsDetailVo.setGoodsImgList(welfareGoodsImgList);
        //集采商品，查品类列表和供应商列表
        if(EmptyUtils.isNotEmpty(welfareGoodsDetailVo.getIsJicai()) && welfareGoodsDetailVo.getIsJicai()==CommonConstants.YES){
            //查品类
            List<WelfareGoodsCategoryRel> goodsCategoryRelList = welfareGoodsCategoryRelService.selectGoodsCategoryRelByGoodsId(goodsId);
            if (EmptyUtils.isNotEmpty(goodsCategoryRelList)) {
                welfareGoodsDetailVo.setGoodsCategoryList(goodsCategoryRelList);
            }
            //查供应商
            List<WelfareGoodsSupplier> goodsSupplierList = welfareGoodsSupplierService.selectGoodsSupplierByGoodsId(goodsId);
            if (EmptyUtils.isNotEmpty(goodsSupplierList)) {
                welfareGoodsDetailVo.setGoodsSupplierList(goodsSupplierList);
            }
        }else{//普通商品，查sku列表和标签列表
            // 商品标签
            List<WelfareGoodsLabel> goodsLabelList = welfareGoodsLabelRelService.selectGoodsLabelListByGoodsId(goodsId,null);
            if (EmptyUtils.isNotEmpty(goodsLabelList)) {
                welfareGoodsDetailVo.setGoodsLabelList(goodsLabelList);
            }
            //查sku
            List<WelfareGoodsAttrVoucherVo> welfareGoodsAttrWithVoucherList = welfareGoodsAttrService.getGoodsAttrWithVoucherByGoodsId(goodsId);
            if (EmptyUtils.isNotEmpty(welfareGoodsAttrWithVoucherList)) {
                welfareGoodsAttrWithVoucherList.forEach(welfareGoodsAttrrWithVoucher -> {
                    if (EmptyUtils.isNotEmpty(welfareGoodsAttrrWithVoucher.getSkuPic())) {
                        welfareGoodsAttrrWithVoucher.setSkuPic(ImageUtils.setImageSrc(welfareGoodsAttrrWithVoucher.getSkuPic()));
                    }
                });
            }
            welfareGoodsDetailVo.setSkuList(welfareGoodsAttrWithVoucherList);
            //虚拟商品api类型
            if (EmptyUtils.isNotEmpty(welfareGoodsDetailVo.getIsApi()) && welfareGoodsDetailVo.getIsApi().equals(CommonConstants.YES)){
                if (EmptyUtils.isNotEmpty(welfareGoodsDetailVo.getMerchantId()) && welfareGoodsDetailVo.getMerchantId().equals(ApiExtractCardConstant.MERCHANT_ID)){
                    welfareGoodsDetailVo.setApiType(WelfareOrderEnum.ORDER_API_TYPE_EXTRACT_CARD.getCode());
                } else {
                    welfareGoodsDetailVo.setApiType(WelfareOrderEnum.ORDER_API_TYPE_RECHARGE.getCode());
                }
            }
        }
        return welfareGoodsDetailVo;
    }

    @Override
    public WelfareGoodsDetailVo getGoodsInfoClassifySku(Integer goodsId) {
        // 商品基本信息
        WelfareGoodsDetailVo welfareGoodsDetailVo = welfareGoodsMapper.selectGoodsInfoDetailById(goodsId);
        if (EmptyUtils.isNotEmpty(welfareGoodsDetailVo.getGoodsType())) {
            // 商品类型
            if (welfareGoodsDetailVo.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_PHYSICAL.getCode())) {
                welfareGoodsDetailVo.setGoodsTypeName(WelfareGoodsEnum.GOODS_TYPE_PHYSICAL.getName());
            } else if (welfareGoodsDetailVo.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getCode())) {
                welfareGoodsDetailVo.setGoodsTypeName(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getName());
            }
        }
        // 商品图片
        WelfareGoodsImg welfareGoodsImg = new WelfareGoodsImg();
        welfareGoodsImg.setGoodsId(goodsId);
        welfareGoodsImg.setStatus(1);
        List<WelfareGoodsImg> welfareGoodsImgList = welfareGoodsImgService.select(welfareGoodsImg);
        //如果图片为空，则有可能是创建企业同步商品时候创建的商品，需要第一次加载详情时候同步商品图片
        if(EmptyUtils.isEmpty(welfareGoodsImgList) && EmptyUtils.isNotEmpty(welfareGoodsDetailVo.getPlatformId())){
            welfareGoodsImg.setGoodsId(welfareGoodsDetailVo.getPlatformId());
            welfareGoodsImgList = welfareGoodsImgService.select(welfareGoodsImg);
            if (EmptyUtils.isNotEmpty(welfareGoodsImgList)) {
                welfareGoodsImgList.forEach(welfareGoodsImg1 -> {
                    welfareGoodsImg1.setGoodsId(goodsId);
                    welfareGoodsImg1.setEnterpriseId(welfareGoodsDetailVo.getEnterpriseId());
                    welfareGoodsImg1.setId(null);
                });
                welfareGoodsImgService.insertList(welfareGoodsImgList);
            }
        }
        if (EmptyUtils.isNotEmpty(welfareGoodsImgList)) {
            welfareGoodsImgList.forEach(welfareGoodsImg1 -> {
                if (EmptyUtils.isNotEmpty(welfareGoodsImg1.getImg())) {
                    welfareGoodsImg1.setImg(ImageUtils.setImageSrc(welfareGoodsImg1.getImg()));
                }
            });
        }
        welfareGoodsDetailVo.setGoodsImgList(welfareGoodsImgList);
        // 商品规格
        List<WelfareGoodsAttr> skuList = getWelfareGoodsAttr(goodsId);
        WelfareGoodsAttr welfareGoodsAttr0 = skuList.get(0);
        int skuLevFlag = 1;// 规格级别判断（判断传过来的规格有几级）至少有一级
        // 规格级别标示(嵌套用于防不规则传参)
        if (EmptyUtils.isNotEmpty(welfareGoodsAttr0.getSecondGroupId())) {
            skuLevFlag = skuLevFlag + 1;
            if (EmptyUtils.isNotEmpty(welfareGoodsAttr0.getThirdGroupId())) {
                skuLevFlag = skuLevFlag + 1;
            }
        }
        List<BigDecimal> priceList = skuList.stream().map(WelfareGoodsAttr::getPrice).collect(Collectors.toList());
        welfareGoodsDetailVo.setLowerPrice(Collections.min(priceList));
        welfareGoodsDetailVo.setUpperPrice(Collections.max(priceList));
        List<WelfareGoodsAttr> skuListSecond = null;
        List<WelfareGoodsAttr> skuListThird = null;
        List<WelfareGoodsAttr> skuListFirst = skuList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(WelfareGoodsAttr::getFirstDetailId))), ArrayList::new));
        skuListFirst = skuListFirst.stream().sorted(Comparator.comparing(WelfareGoodsAttr::getId)).collect(Collectors.toList());// 排序
        if (skuLevFlag > 1) {
            skuListSecond = skuList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(WelfareGoodsAttr::getSecondDetailId))), ArrayList::new));
            skuListSecond = skuListSecond.stream().sorted(Comparator.comparing(WelfareGoodsAttr::getId)).collect(Collectors.toList());// 排序
        }
        if (skuLevFlag > 2) {
            skuListThird = skuList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(WelfareGoodsAttr::getThirdDetailId))), ArrayList::new));
            skuListThird = skuListThird.stream().sorted(Comparator.comparing(WelfareGoodsAttr::getId)).collect(Collectors.toList());// 排序
        }
        welfareGoodsDetailVo.setSkuLevFlag(skuLevFlag);
        welfareGoodsDetailVo.setFirstGroupId(welfareGoodsAttr0.getFirstGroupId());
        welfareGoodsDetailVo.setFirstGroupName(welfareGoodsAttr0.getFirstGroupName());
        welfareGoodsDetailVo.setFirstSkuList(skuListFirst);
        welfareGoodsDetailVo.setSecondGroupId(welfareGoodsAttr0.getSecondGroupId());
        welfareGoodsDetailVo.setSecondGroupName(welfareGoodsAttr0.getSecondGroupName());
        welfareGoodsDetailVo.setSecondSkuList(skuListSecond);
        welfareGoodsDetailVo.setThirdGroupId(welfareGoodsAttr0.getThirdGroupId());
        welfareGoodsDetailVo.setThirdGroupName(welfareGoodsAttr0.getThirdGroupName());
        welfareGoodsDetailVo.setThirdSkuList(skuListThird);
        // 商品标签
        List<WelfareGoodsLabel> goodsLabelList = welfareGoodsLabelRelService.selectGoodsLabelListByGoodsId(goodsId,2);
        if (EmptyUtils.isNotEmpty(goodsLabelList)) {
            welfareGoodsDetailVo.setGoodsLabelList(goodsLabelList);
        }
        if (EmptyUtils.isNotEmpty(welfareGoodsDetailVo.getHolidayPostpone()) && welfareGoodsDetailVo.getHolidayPostpone().equals(1)){
            if (EmptyUtils.isNotEmpty(welfareGoodsDetailVo.getDeliveryDes())){
                welfareGoodsDetailVo.setDeliveryDes(welfareGoodsDetailVo.getDeliveryDes() + "，节假日顺延");
            }
        }
        return welfareGoodsDetailVo;
    }

    @Override
    public WelfareGoodsManageVo getGoodsPriceAndQuantityByGoodsId(Integer goodsId) {
        return welfareGoodsMapper.selectGoodsPriceAndQuantityByGoodsId(goodsId);
    }

    @Master
    @Override
    public Map<String, Object> addGoodsManage(WelfareGoodsManageAddDto welfareGoodsManageAddDto,LoginSysAdminVo loginInfo) {
        Map<String, Object> resMap = new HashMap<>();
        WelfareGoods welfareGoods = new WelfareGoods();
        // 对参数进行校验，并且组拼welfareGoods对象
        if (validGoodsManageAndBuildParams(resMap, welfareGoodsManageAddDto, welfareGoods)) {
            return resMap;
        }
        // 添加商品信息
        welfareGoods.setCreateTime(new Date());
        welfareGoods.setStatus(1);
        welfareGoods.setIsShow(1);
        welfareGoods.setGoodsConvertQuantity(0);
        welfareGoods.setMarketPrice(welfareGoodsManageAddDto.getMarketPrice());
        //默认添加普通/非集采商品
        if(EmptyUtils.isEmpty(welfareGoodsManageAddDto.getIsJicai())){
            welfareGoods.setIsJicai(CommonConstants.NO);
        }else{
            welfareGoods.setIsJicai(welfareGoodsManageAddDto.getIsJicai());
        }
        welfareGoods.setEnterpriseId(welfareGoodsManageAddDto.getEnterpriseId());
        welfareGoods.setSyncNonSelfSupport(CommonConstants.YES);
        welfareGoodsMapper.insertUseGeneratedKeys(welfareGoods);
        //如果是保存上架，则新增日志
        if (welfareGoodsManageAddDto.getOptType() == WelfareGoodsEnum.GOODS_OPT_TYPE_SHELVES.getCode()) {
            operationLogService.saveOperationLog(welfareGoods.getId(),"新添加商品["+welfareGoods.getGoodsName()+"]并上架",OperationConstant.TypeEnum.GOODS_ADD_SHELVES.getType(),loginInfo.getId(),loginInfo.getUserName());
        }else{
            operationLogService.saveOperationLog(welfareGoods.getId(),"新添加商品["+welfareGoods.getGoodsName()+"]并保存到草稿箱",OperationConstant.TypeEnum.GOODS_ADD_TO_DRAFT.getType(),loginInfo.getId(),loginInfo.getUserName());
        }
        //默认商品排序为999
        Integer goodsSort = 9999;
        Integer goodsId = welfareGoods.getId();
        // 添加商品标签信息
        List<Integer> labelIdList = welfareGoodsManageAddDto.getLabelIdList();
        if (EmptyUtils.isNotEmpty(labelIdList) && labelIdList.size() > 0) {
            List<WelfareGoodsLabelRel> welfareGoodsLabelRelList = new ArrayList<>();
            for (Integer labelId : labelIdList) {
                WelfareGoodsLabelRel welfareGoodsLabelRelAdd = new WelfareGoodsLabelRel();
                welfareGoodsLabelRelAdd.setGoodsId(goodsId);
                welfareGoodsLabelRelAdd.setLabelId(labelId);
                welfareGoodsLabelRelList.add(welfareGoodsLabelRelAdd);
                //判断是否有选择置顶标签，若有，则修改商品排序值为0
                if(goodsSort == 9999){
                    WelfareGoodsLabel wgl = welfareGoodsLabelService.selectByPrimaryKey(labelId);
                    if(EmptyUtils.isNotEmpty(wgl) && wgl.getIsTop()==CommonConstants.YES){
                        goodsSort = 0;
                    }
                }
            }
            welfareGoodsLabelRelService.insertList(welfareGoodsLabelRelList);
            //判断是否有选择置顶标签，若有，则修改商品排序值为0
            if(goodsSort == 0 ){
                welfareGoods.setSort(0);
                welfareGoods.setUpdateTime(new Date());
                welfareGoodsMapper.updateByPrimaryKeySelective(welfareGoods);
            }
        }
        // 添加规格组信息
        if (EmptyUtils.isNotEmpty(welfareGoodsManageAddDto.getSkuList())) {
            int skuLevFlag = 0;// 规格级别判断（判断传过来的规格有几级）至少有一级
            List<WelfareGoodsAttr> welfareGoodsManageAddDtoSkuList = welfareGoodsManageAddDto.getSkuList();
            WelfareGoodsAttr welfareGoodsManageSkuAddDto0 = welfareGoodsManageAddDtoSkuList.get(0);
            // 嵌套用于防不规则传参(规格级别标示)
            if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto0.getFirstGroupName())) {
                skuLevFlag = skuLevFlag + 1;
                if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto0.getSecondGroupName())) {
                    skuLevFlag = skuLevFlag + 1;
                    if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto0.getThirdGroupName())) {
                        skuLevFlag = skuLevFlag + 1;
                    }
                }
            }
            // 如果不是草稿箱，规格必录
            if (!welfareGoodsManageAddDto.getOptType().equals(WelfareGoodsEnum.GOODS_OPT_TYPE_DRAFT.getCode()) && skuLevFlag < 1) {
                resMap.put("code", 1916);
                resMap.put("msg", "请填写规格信息");
                return resMap;
            }
            List<WelfareGoodsAttr> welfareGoodsManageAddDtoSkuListFirst = null;
            List<WelfareGoodsAttr> welfareGoodsManageAddDtoSkuListSecond = null;
            List<WelfareGoodsAttr> welfareGoodsManageAddDtoSkuListThird = null;
            if (skuLevFlag > 0) {
                welfareGoodsManageAddDtoSkuListFirst = welfareGoodsManageAddDtoSkuList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(WelfareGoodsAttr::getFirstDetailName))), ArrayList::new));
            }
            if (skuLevFlag > 1) {
                welfareGoodsManageAddDtoSkuListSecond = welfareGoodsManageAddDtoSkuList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(WelfareGoodsAttr::getSecondDetailName))), ArrayList::new));
            }
            if (skuLevFlag > 2) {
                welfareGoodsManageAddDtoSkuListThird = welfareGoodsManageAddDtoSkuList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(WelfareGoodsAttr::getThirdDetailName))), ArrayList::new));
            }
            // 新增规格组数据
            List<WelfareGoodsAttrGroup> welfareGoodsAttrGroupList = new ArrayList<>();
            // 一级
            if (skuLevFlag > 0) {
                WelfareGoodsAttrGroup welfareGoodsAttrGroupFirst = new WelfareGoodsAttrGroup();
                if (EmptyUtils.isEmpty(welfareGoodsManageSkuAddDto0.getFirstGroupName())) {
                    throw new CommonException("无效的规格组名");
                }
                welfareGoodsAttrGroupFirst.setGroupName(welfareGoodsManageSkuAddDto0.getFirstGroupName());
                welfareGoodsAttrGroupFirst.setCreateTime(new Date());
                welfareGoodsAttrGroupFirst.setSort(1);
                welfareGoodsAttrGroupFirst.setStatus(1);
                welfareGoodsAttrGroupList.add(welfareGoodsAttrGroupFirst);
            }
            // 二级
            if (skuLevFlag > 1) {
                WelfareGoodsAttrGroup welfareGoodsAttrGroupSecond = new WelfareGoodsAttrGroup();
                if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto0.getSecondGroupName())) {
                    welfareGoodsAttrGroupSecond.setGroupName(welfareGoodsManageSkuAddDto0.getSecondGroupName());
                } else {
                    throw new CommonException("无效的规格组名");
                }
                welfareGoodsAttrGroupSecond.setCreateTime(new Date());
                welfareGoodsAttrGroupSecond.setSort(2);
                welfareGoodsAttrGroupSecond.setStatus(1);
                welfareGoodsAttrGroupList.add(welfareGoodsAttrGroupSecond);
            }
            // 三级
            if (skuLevFlag > 2) {
                WelfareGoodsAttrGroup welfareGoodsAttrGroupThird = new WelfareGoodsAttrGroup();
                if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto0.getThirdGroupName())) {
                    welfareGoodsAttrGroupThird.setGroupName(welfareGoodsManageSkuAddDto0.getThirdGroupName());
                } else {
                    throw new CommonException("无效的规格组名");
                }
                welfareGoodsAttrGroupThird.setCreateTime(new Date());
                welfareGoodsAttrGroupThird.setSort(3);
                welfareGoodsAttrGroupThird.setStatus(1);
                welfareGoodsAttrGroupList.add(welfareGoodsAttrGroupThird);
            }
            if (skuLevFlag > 0) {
                welfareGoodsAttrGroupService.insertList(welfareGoodsAttrGroupList);
            }
            List<WelfareGoodsAttrGroupRel> welfareGoodsAttrGroupRelList = new ArrayList<>();
            // 把规格组以规格组sort和规格组名为key、groupId为值放入到Map中
            Map<String, Integer> groupIdMap = new HashMap<>();
            for (WelfareGoodsAttrGroup welfareGoodsAttrGroup : welfareGoodsAttrGroupList) {
                String key = welfareGoodsAttrGroup.getSort() + welfareGoodsAttrGroup.getGroupName();
                groupIdMap.put(key, welfareGoodsAttrGroup.getId());
                // 添加到商品规格组关联表
                WelfareGoodsAttrGroupRel welfareGoodsAttrGroupRel = new WelfareGoodsAttrGroupRel();
                welfareGoodsAttrGroupRel.setGoodsId(goodsId);
                welfareGoodsAttrGroupRel.setGroupId(welfareGoodsAttrGroup.getId());
                welfareGoodsAttrGroupRel.setLevel(welfareGoodsAttrGroup.getSort());
                welfareGoodsAttrGroupRel.setCreateTime(new Date());
                welfareGoodsAttrGroupRel.setStatus(1);
                welfareGoodsAttrGroupRelList.add(welfareGoodsAttrGroupRel);
            }
            // 添加到商品规格组关联表
            welfareGoodsAttrGroupRelService.insertList(welfareGoodsAttrGroupRelList);
            // 添加不同级别规格值到detail表
            List<WelfareGoodsAttrDetail> welfareGoodsAttrDetailList = new ArrayList<>();
            // 一级规格
            Integer firstGroupId = null;
            if (skuLevFlag > 0) {
                String firstGroupKey = 1 + welfareGoodsManageSkuAddDto0.getFirstGroupName();
                firstGroupId = groupIdMap.get(firstGroupKey);
                for (WelfareGoodsAttr welfareGoodsManageSkuAddDto : welfareGoodsManageAddDtoSkuListFirst) {
                    WelfareGoodsAttrDetail welfareGoodsAttrDetail = new WelfareGoodsAttrDetail();
                    welfareGoodsAttrDetail.setDetailName(welfareGoodsManageSkuAddDto.getFirstDetailName());
                    welfareGoodsAttrDetail.setGroupId(firstGroupId);
                    welfareGoodsAttrDetail.setCreateTime(new Date());
                    welfareGoodsAttrDetail.setStatus(1);
                    welfareGoodsAttrDetailList.add(welfareGoodsAttrDetail);
                }
            }
            // 二级规格
            Integer secondGroupId = null;
            if (skuLevFlag > 1) {
                String secondGroupKey = 2 + welfareGoodsManageSkuAddDto0.getSecondGroupName();
                secondGroupId = groupIdMap.get(secondGroupKey);
                for (WelfareGoodsAttr welfareGoodsManageSkuAddDto : welfareGoodsManageAddDtoSkuListSecond) {
                    WelfareGoodsAttrDetail welfareGoodsAttrDetail = new WelfareGoodsAttrDetail();
                    welfareGoodsAttrDetail.setDetailName(welfareGoodsManageSkuAddDto.getSecondDetailName());
                    welfareGoodsAttrDetail.setGroupId(secondGroupId);
                    welfareGoodsAttrDetail.setCreateTime(new Date());
                    welfareGoodsAttrDetail.setStatus(1);
                    welfareGoodsAttrDetailList.add(welfareGoodsAttrDetail);
                }
            }
            // 三级规格
            Integer thirdGroupId = null;
            if (skuLevFlag > 2) {
                String thirdGroupKey = 3 + welfareGoodsManageSkuAddDto0.getThirdGroupName();
                thirdGroupId = groupIdMap.get(thirdGroupKey);
                for (WelfareGoodsAttr welfareGoodsManageSkuAddDto : welfareGoodsManageAddDtoSkuListThird) {
                    WelfareGoodsAttrDetail welfareGoodsAttrDetail = new WelfareGoodsAttrDetail();
                    welfareGoodsAttrDetail.setDetailName(welfareGoodsManageSkuAddDto.getThirdDetailName());
                    welfareGoodsAttrDetail.setGroupId(thirdGroupId);
                    welfareGoodsAttrDetail.setCreateTime(new Date());
                    welfareGoodsAttrDetail.setStatus(1);
                    welfareGoodsAttrDetailList.add(welfareGoodsAttrDetail);
                }
            }
            if (skuLevFlag > 0) {
                welfareGoodsAttrDetailService.insertList(welfareGoodsAttrDetailList);
            }
            // 把规格值以规格组级别和规格值名为key、detailId为值放入到Map中
            Map<String, Integer> groupDetailIdMap = new HashMap<>();
            for (WelfareGoodsAttrDetail welfareGoodsAttrDetail : welfareGoodsAttrDetailList) {
                String key = "";
                if (welfareGoodsAttrDetail.getGroupId().equals(firstGroupId)) {
                    key = 1 + welfareGoodsAttrDetail.getDetailName();
                }
                if (skuLevFlag > 1 && welfareGoodsAttrDetail.getGroupId().equals(secondGroupId)) {
                    key = 2 + welfareGoodsAttrDetail.getDetailName();
                }
                if (skuLevFlag > 2 && welfareGoodsAttrDetail.getGroupId().equals(thirdGroupId)) {
                    key = 3 + welfareGoodsAttrDetail.getDetailName();
                }
                groupDetailIdMap.put(key, welfareGoodsAttrDetail.getId());
            }
            // 添加sku信息到sku表
            List<WelfareGoodsAttr> welfareGoodsAttrList = new ArrayList<>();
            for (int i = 0; i < welfareGoodsManageAddDtoSkuList.size(); i++) {
                WelfareGoodsAttr welfareGoodsManageSkuAddDto = welfareGoodsManageAddDtoSkuList.get(i);
                WelfareGoodsAttr welfareGoodsAttr = new WelfareGoodsAttr();
                welfareGoodsAttr.setGoodsId(goodsId);
                // 设置一级规格信息
                welfareGoodsAttr.setFirstGroupId(firstGroupId);
                welfareGoodsAttr.setFirstGroupName(welfareGoodsManageSkuAddDto.getFirstGroupName());
                if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getFirstDetailName())) {
                    welfareGoodsAttr.setFirstDetailName(welfareGoodsManageSkuAddDto.getFirstDetailName());
                } else {
                    throw new CommonException("无效的规格值");
                }
                String firstDetailKey = 1 + welfareGoodsManageSkuAddDto.getFirstDetailName();
                Integer firstDetailId = groupDetailIdMap.get(firstDetailKey);
                welfareGoodsAttr.setFirstDetailId(firstDetailId);
                // 设置二级规格信息
                if (skuLevFlag > 1) {
                    welfareGoodsAttr.setSecondGroupId(secondGroupId);
                    welfareGoodsAttr.setSecondGroupName(welfareGoodsManageSkuAddDto.getSecondGroupName());
                    welfareGoodsAttr.setSecondDetailName(welfareGoodsManageSkuAddDto.getSecondDetailName());
                    String secondDetailKey = 2 + welfareGoodsManageSkuAddDto.getSecondDetailName();
                    Integer secondDetailId = groupDetailIdMap.get(secondDetailKey);
                    welfareGoodsAttr.setSecondDetailId(secondDetailId);
                }
                // 设置三级规格信息
                if (skuLevFlag > 2) {
                    welfareGoodsAttr.setThirdGroupId(thirdGroupId);
                    welfareGoodsAttr.setThirdGroupName(welfareGoodsManageSkuAddDto.getThirdGroupName());
                    welfareGoodsAttr.setThirdDetailName(welfareGoodsManageSkuAddDto.getThirdDetailName());
                    String thirdDetailKey = 3 + welfareGoodsManageSkuAddDto.getThirdDetailName();
                    Integer thirdDetailId = groupDetailIdMap.get(thirdDetailKey);
                    welfareGoodsAttr.setThirdDetailId(thirdDetailId);
                }
                // 设置价格、成本价格、库存或者卡密id
                if (welfareGoodsManageSkuAddDto.getPrice() == null) {
                    throw new CommonException("请填写价格信息");
                } else {
                    welfareGoodsAttr.setPrice(welfareGoodsManageSkuAddDto.getPrice());
                }
                if (welfareGoodsManageSkuAddDto.getCostPrice() == null) {
                    throw new CommonException("请填写成本价信息");
                } else {
                    welfareGoodsAttr.setCostPrice(welfareGoodsManageSkuAddDto.getCostPrice());
                }
                // 规格图片
                if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getSkuPic())) {
                    welfareGoodsAttr.setSkuPic(welfareGoodsManageSkuAddDto.getSkuPic());
                }
                // 实体商品库存为券密组上带过来的库存
                if (welfareGoodsManageAddDto.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_PHYSICAL.getCode())) {
                    if (welfareGoodsManageSkuAddDto.getQuantity() == null) {
                        throw new CommonException("请填写库存数量");
                    } else {
                        welfareGoodsAttr.setQuantity(welfareGoodsManageSkuAddDto.getQuantity());// 库存数量
                    }
                }
                // 虚拟商品需要选择关联类型
                else if (welfareGoodsManageAddDto.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getCode())) {
                    if (EmptyUtils.isEmpty(welfareGoodsManageSkuAddDto.getAttrContactType())) {
                        throw new CommonException("请选择关联类型");
                    }
                    // 券密组类型需要选择券密组
                    if (welfareGoodsManageSkuAddDto.getAttrContactType().equals(WelfareGoodsEnum.GOODS_ATTR_TYPE_VIRTUAL_VOUCHER.getCode())) {
                        if (welfareGoodsManageSkuAddDto.getVoucherSecretGroupId() == null) {
                            throw new CommonException("请填写券密组信息（虚拟商品）");
                        }
                        if (welfareGoodsManageSkuAddDto.getVoucherSecretGroupId() > 0) {
                            // 虚拟商品库存数量从券密组获取
                            WelfareGoodsAttr welfareGoodsAttrSelect = new WelfareGoodsAttr();
                            welfareGoodsAttrSelect.setVoucherSecretGroupId(welfareGoodsManageSkuAddDto.getVoucherSecretGroupId());
                            welfareGoodsAttrSelect.setStatus(1);
                            Integer attrCount = welfareGoodsAttrService.selectCount(welfareGoodsAttrSelect);
                            if (attrCount > 0) {
                                throw new CommonException("券密组已被绑定");
                            }
                            VoucherSecretGroupSellVo voucherSecretGroupSellVo = welfareVoucherSecretGroupService.getVoucherSecretGroupWithSellInfo(welfareGoodsManageSkuAddDto.getVoucherSecretGroupId());
                            if (EmptyUtils.isNotEmpty(voucherSecretGroupSellVo) && EmptyUtils.isNotEmpty(voucherSecretGroupSellVo.getCountIsNotSell())) {
                                welfareGoodsAttr.setQuantity(voucherSecretGroupSellVo.getCountIsNotSell());
                            } else {
                                throw new CommonException("券密组已失效");
                            }
                        }
                        welfareGoodsAttr.setVoucherSecretGroupId(welfareGoodsManageSkuAddDto.getVoucherSecretGroupId());// 券密组id
                        if (welfareGoodsManageSkuAddDto.getVoucherSecretGroupId().equals(0)) {
                            welfareGoodsAttr.setQuantity(0);
                        }
                    }
                    // 充值类型需要选择产品编码及产品名
                    else if (welfareGoodsManageSkuAddDto.getAttrContactType().equals(WelfareGoodsEnum.GOODS_ATTR_TYPE_VIRTUAL_RECHARGE.getCode())) {
                        if (EmptyUtils.isEmpty(welfareGoodsManageSkuAddDto.getProductId())) {
                            throw new CommonException("请填写券密组信息（虚拟商品）");
                        } else {
                            welfareGoodsAttr.setProductId(welfareGoodsManageSkuAddDto.getProductId());
                        }
                        if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getProductName())) {
                            welfareGoodsAttr.setProductName(welfareGoodsManageSkuAddDto.getProductName());
                        }
                        welfareGoodsAttr.setAttrContactType(welfareGoodsManageSkuAddDto.getAttrContactType());
                    } else {
                        throw new CommonException("无效的关联类型");
                    }
                } else {
                    if(EmptyUtils.isEmpty(welfareGoodsManageAddDto.getIsJicai())){
                        throw new CommonException("无效的商品类型");
                    }
                }
                welfareGoodsAttr.setLockQuantity(0);// 新增商品预占数量初始化
                welfareGoodsAttr.setCreateTime(new Date());
                welfareGoodsAttr.setStatus(1);
                welfareGoodsAttr.setSort(i + 1);
                welfareGoodsAttrList.add(welfareGoodsAttr);
            }
            if (skuLevFlag > 0) {
                welfareGoodsAttrService.insertList(welfareGoodsAttrList);
            }
        }
        // 添加商品图片
        if (EmptyUtils.isNotEmpty(welfareGoodsManageAddDto.getImgList())) {
            List<WelfareGoodsImg> welfareGoodsImgList = new ArrayList<>();
            for (WelfareGoodsImg welfareGoodsImg : welfareGoodsManageAddDto.getImgList()) {
                welfareGoodsImg.setGoodsId(goodsId);
                welfareGoodsImg.setCreateTime(new Date());
                welfareGoodsImg.setStatus(1);
                welfareGoodsImgList.add(welfareGoodsImg);
            }
            welfareGoodsImgService.insertList(welfareGoodsImgList);
        }

        // 添加商品品类（集采商品有）
        List<Integer> categoryIdList = welfareGoodsManageAddDto.getCategoryIdList();
        if (EmptyUtils.isNotEmpty(categoryIdList) && categoryIdList.size() > 0) {
            List<WelfareGoodsCategoryRel> welfareGoodsCategoryRelList = new ArrayList<>();
            for (Integer categoryId : categoryIdList) {
                WelfareGoodsCategoryRel welfareGoodsCategoryRelAdd = new WelfareGoodsCategoryRel();
                welfareGoodsCategoryRelAdd.setGoodsId(goodsId);
                welfareGoodsCategoryRelAdd.setCategoryId(categoryId);
                welfareGoodsCategoryRelList.add(welfareGoodsCategoryRelAdd);
            }
            welfareGoodsCategoryRelService.insertList(welfareGoodsCategoryRelList);
        }
        // 添加商品供应商（集采商品有）
        if (EmptyUtils.isNotEmpty(welfareGoodsManageAddDto.getSupplierList())) {
            for (WelfareGoodsSupplier welfareGoodsSupplier : welfareGoodsManageAddDto.getSupplierList()) {
                welfareGoodsSupplier.setGoodsId(goodsId);
                welfareGoodsSupplier.setCreateTime(new Date());
                welfareGoodsSupplier.setStatus(1);
            }
            welfareGoodsSupplierService.insertList(welfareGoodsManageAddDto.getSupplierList());
        }
        //如果是上架非集采商品，则需要同步商品到企业端
        if(welfareGoodsManageAddDto.getOptType().equals(WelfareGoodsEnum.GOODS_OPT_TYPE_SHELVES.getCode()) && EmptyUtils.isEmpty(welfareGoodsManageAddDto.getIsJicai())){
            resMap.put("goodsId", goodsId);
        }
        resMap.put("code", 1);
        resMap.put("msg", "success");
        return resMap;
    }

    /**
     * 获取规格组id，优先从已有Map获取，如果不包含，则获取新的Map里面的（为新增）
     *
     * @param groupIdMapOld 规格组id Map
     * @param groupIdMapNew 规格组id Map
     * @param sort          排序级别
     * @return java.lang.Integer
     * @author ChenLong
     * @date 2021-06-30 10:41:09
     **/
    private Integer getGroupIdFromOldBeforeBySort(Map<Integer, Integer> groupIdMapOld, Map<Integer, Integer> groupIdMapNew, Integer sort) {
        if (groupIdMapOld.containsKey(sort)) {
            return groupIdMapOld.get(sort);
        } else {
            return groupIdMapNew.get(sort);
        }
    }

    @Override
    public Map<String, Object> updateGoodsManage(WelfareGoodsManageAddDto welfareGoodsManageAddDto) {
        Map<String, Object> resMap = new HashMap<>();
        WelfareGoods welfareGoods = new WelfareGoods();
        // 对参数进行校验，并且组拼welfareGoods对象
        if (validGoodsManageAndBuildParams(resMap, welfareGoodsManageAddDto, welfareGoods)) {
            return resMap;
        }
        if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getGoodsId())) {
            resMap.put("code", 1914);
            resMap.put("msg", "无效的商品id");
            return resMap;
        }
        WelfareGoods welfareGoodsRes = welfareGoodsMapper.selectByPrimaryKey(welfareGoodsManageAddDto.getGoodsId());
        Date createTime = welfareGoodsRes.getCreateTime();
        Integer goodsConvertQuantity = welfareGoodsRes.getGoodsConvertQuantity();
        // 修改商品基本信息
        welfareGoods.setId(welfareGoodsManageAddDto.getGoodsId());
        welfareGoods.setUpdateTime(new Date());
        //welfareGoods.setStatus(1);
        welfareGoods.setIsJicai(welfareGoodsRes.getIsJicai());
        welfareGoods.setMarketPrice(welfareGoodsManageAddDto.getMarketPrice());
        // 如下两个值，前端不传参，直接获取数据库里面的值
        welfareGoods.setCreateTime(createTime != null ? createTime : new Date());
        welfareGoods.setIsShow(welfareGoodsRes.getIsShow());
        welfareGoods.setGoodsConvertQuantity(goodsConvertQuantity != null ? goodsConvertQuantity : 0);
        welfareGoodsMapper.updateByPrimaryKeySelective(welfareGoods);
        //记录修改日志
        if(welfareGoodsManageAddDto.getOptType().equals(WelfareGoodsEnum.GOODS_OPT_TYPE_DRAFT.getCode())){
            operationLogService.saveOperationLog(welfareGoods.getId(),"编辑商品["+welfareGoods.getGoodsName()+"],存入草稿箱",OperationConstant.TypeEnum.GOODS_ADD_TO_DRAFT.getType(),welfareGoodsManageAddDto.getUpdater(),welfareGoodsManageAddDto.getUpdaterName());
        }else if(welfareGoodsManageAddDto.getOptType().equals(WelfareGoodsEnum.GOODS_OPT_TYPE_DOWN.getCode())){
            operationLogService.saveOperationLog(welfareGoods.getId(),"下架状态编辑商品["+welfareGoods.getGoodsName()+"],不修改状态",OperationConstant.TypeEnum.GOODS_EDIT_INFO.getType(),welfareGoodsManageAddDto.getUpdater(),welfareGoodsManageAddDto.getUpdaterName());
        }else{
            operationLogService.saveOperationLog(welfareGoods.getId(),"编辑商品["+welfareGoods.getGoodsName()+"]",OperationConstant.TypeEnum.GOODS_EDIT_INFO.getType(),welfareGoodsManageAddDto.getUpdater(),welfareGoodsManageAddDto.getUpdaterName());
        }
        //默认商品排序为999
        Integer goodsSort = 9999;
        // 先删除原标签列表
        WelfareGoodsLabelRel welfareGoodsLabelRelDeleteParam = new WelfareGoodsLabelRel();
        welfareGoodsLabelRelDeleteParam.setGoodsId(welfareGoodsManageAddDto.getGoodsId());
        welfareGoodsLabelRelService.delete(welfareGoodsLabelRelDeleteParam);
        /*Example example = new Example(WelfareGoodsLabelRel.class);
        example.createCriteria().andEqualTo("goodsId", welfareGoodsManageAddDto.getGoodsId());
        welfareGoodsLabelRelService.deleteByExample(example);*/
        // 修改商品标签信息
        List<Integer> labelIdList = welfareGoodsManageAddDto.getLabelIdList();
        if (EmptyUtils.isNotEmpty(labelIdList) && labelIdList.size() > 0) {
            // 再更新新的标签
            List<WelfareGoodsLabelRel> welfareGoodsLabelRelList = new ArrayList<>();
            for (Integer labelId : labelIdList) {
                WelfareGoodsLabelRel welfareGoodsLabelRelAdd = new WelfareGoodsLabelRel();
                welfareGoodsLabelRelAdd.setGoodsId(welfareGoodsManageAddDto.getGoodsId());
                welfareGoodsLabelRelAdd.setLabelId(labelId);
                welfareGoodsLabelRelList.add(welfareGoodsLabelRelAdd);
                //判断是否有选择置顶标签，若有，则修改商品排序值为0
                if(goodsSort == 9999){
                    WelfareGoodsLabel wgl = welfareGoodsLabelService.selectByPrimaryKey(labelId);
                    if(EmptyUtils.isNotEmpty(wgl) && wgl.getIsTop()==CommonConstants.YES){
                        goodsSort = 0;
                    }
                }
            }
            welfareGoodsLabelRelService.insertList(welfareGoodsLabelRelList);
        }
        //修改商品排序值
        welfareGoods.setSort(goodsSort);
        welfareGoods.setUpdateTime(new Date());
        welfareGoodsMapper.updateByPrimaryKeySelective(welfareGoods);
        // 添加规格组信息
        if (EmptyUtils.isNotEmpty(welfareGoodsManageAddDto.getSkuList())) {
            // 从以一条sku里面拿到规格组信息
            List<WelfareGoodsAttr> welfareGoodsManageAddDtoSkuList = welfareGoodsManageAddDto.getSkuList();
            int skuLevFlag = 0;// 规格级别判断（判断传过来的规格有几级）至少有一级
            WelfareGoodsAttr welfareGoodsManageSkuAddDto0 = welfareGoodsManageAddDtoSkuList.get(0);
            // 规格级别标示(嵌套用于防不规则传参)
            if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto0.getFirstGroupName())) {
                skuLevFlag = skuLevFlag + 1;
                if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto0.getSecondGroupName())) {
                    skuLevFlag = skuLevFlag + 1;
                    if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto0.getThirdGroupName())) {
                        skuLevFlag = skuLevFlag + 1;
                    }
                }
            }
            List<WelfareGoodsAttr> welfareGoodsManageAddDtoSkuListFirst = null;
            List<WelfareGoodsAttr> welfareGoodsManageAddDtoSkuListSecond = null;
            List<WelfareGoodsAttr> welfareGoodsManageAddDtoSkuListThird = null;
            // 规格组id（已有的规格组有规格组id，新增的规格组没有规格id）
            List<Integer> firstGroupIdList = null;
            List<Integer> secondGroupIdList = null;
            List<Integer> thirdGroupIdList = null;
            if (skuLevFlag > 0) {
                welfareGoodsManageAddDtoSkuListFirst = welfareGoodsManageAddDtoSkuList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(WelfareGoodsAttr::getFirstDetailName))), ArrayList::new));
                // 获取该规格组里面是否有groupId（如果有说明该规格组已存在）
                firstGroupIdList = welfareGoodsManageAddDtoSkuList.stream().filter(s -> s.getFirstGroupId() != null && EmptyUtils.isNotEmpty(s.getFirstGroupId())).map(WelfareGoodsAttr::getFirstGroupId).collect(Collectors.toList());
            }
            if (skuLevFlag > 1) {
                welfareGoodsManageAddDtoSkuListSecond = welfareGoodsManageAddDtoSkuList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(WelfareGoodsAttr::getSecondDetailName))), ArrayList::new));
                secondGroupIdList = welfareGoodsManageAddDtoSkuList.stream().filter(s -> s.getSecondGroupId() != null && EmptyUtils.isNotEmpty(s.getSecondGroupId())).map(WelfareGoodsAttr::getSecondGroupId).collect(Collectors.toList());
            }
            if (skuLevFlag > 2) {
                welfareGoodsManageAddDtoSkuListThird = welfareGoodsManageAddDtoSkuList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(WelfareGoodsAttr::getThirdDetailName))), ArrayList::new));
                thirdGroupIdList = welfareGoodsManageAddDtoSkuList.stream().filter(s -> s.getThirdGroupId() != null && EmptyUtils.isNotEmpty(s.getThirdGroupId())).map(WelfareGoodsAttr::getThirdGroupId).collect(Collectors.toList());
            }
            // 查询该商品规格组关联表（删除商品原来关联表、规格组、规格值记录）
            Example goodsAttrGroupRelExample = new Example(WelfareGoodsAttrGroupRel.class);
            goodsAttrGroupRelExample.createCriteria().andEqualTo("goodsId", welfareGoodsManageAddDto.getGoodsId());
            List<WelfareGoodsAttrGroupRel> welfareGoodsAttrGroupRelListRes = welfareGoodsAttrGroupRelService.selectByExample(goodsAttrGroupRelExample);
            if (EmptyUtils.isNotEmpty(welfareGoodsAttrGroupRelListRes) && welfareGoodsAttrGroupRelListRes.size() > 0) {
                List<Integer> oldGoodsGroupIdList = welfareGoodsAttrGroupRelListRes.stream().map(WelfareGoodsAttrGroupRel::getGroupId).collect(Collectors.toList());
                // 删除规格组记录
                Example goodsAttrGroupDelExample = new Example(WelfareGoodsAttrGroup.class);
                goodsAttrGroupDelExample.createCriteria().andIn("id", oldGoodsGroupIdList);
                welfareGoodsAttrGroupService.deleteByExample(goodsAttrGroupDelExample);
                // 删除规格值记录
                Example goodsAttrDetailDelExample = new Example(WelfareGoodsAttrDetail.class);
                goodsAttrDetailDelExample.createCriteria().andIn("groupId", oldGoodsGroupIdList);
                welfareGoodsAttrDetailService.deleteByExample(goodsAttrDetailDelExample);
                // 删除原商品规格关联记录
                welfareGoodsAttrGroupRelService.deleteByExample(goodsAttrGroupRelExample);
            }
            // 新增规格组
            WelfareGoodsAttrGroup welfareGoodsAttrGroupFirst = new WelfareGoodsAttrGroup();
            WelfareGoodsAttrGroup welfareGoodsAttrGroupSecond = new WelfareGoodsAttrGroup();
            WelfareGoodsAttrGroup welfareGoodsAttrGroupThird = new WelfareGoodsAttrGroup();
            List<WelfareGoodsAttrGroup> welfareGoodsAttrGroupList = new ArrayList<>();
            Map<Integer, Integer> groupIdMapOld = new HashMap<>();
            if (skuLevFlag > 0) {
                if (EmptyUtils.isNotEmpty(firstGroupIdList) && firstGroupIdList.size() > 0) {
                    welfareGoodsAttrGroupFirst.setId(firstGroupIdList.get(0));
                    groupIdMapOld.put(1, firstGroupIdList.get(0));
                }
                welfareGoodsAttrGroupFirst.setGroupName(welfareGoodsManageSkuAddDto0.getFirstGroupName());
                welfareGoodsAttrGroupFirst.setCreateTime(new Date());
                welfareGoodsAttrGroupFirst.setUpdateTime(new Date());
                welfareGoodsAttrGroupFirst.setSort(1);
                welfareGoodsAttrGroupFirst.setStatus(1);
                welfareGoodsAttrGroupList.add(welfareGoodsAttrGroupFirst);
            }
            if (skuLevFlag > 1) {
                if (EmptyUtils.isNotEmpty(secondGroupIdList) && secondGroupIdList.size() > 0) {
                    welfareGoodsAttrGroupSecond.setId(secondGroupIdList.get(0));
                    groupIdMapOld.put(2, secondGroupIdList.get(0));
                }
                welfareGoodsAttrGroupSecond.setGroupName(welfareGoodsManageSkuAddDto0.getSecondGroupName());
                welfareGoodsAttrGroupSecond.setCreateTime(new Date());
                welfareGoodsAttrGroupSecond.setUpdateTime(new Date());
                welfareGoodsAttrGroupSecond.setSort(2);
                welfareGoodsAttrGroupSecond.setStatus(1);
                welfareGoodsAttrGroupList.add(welfareGoodsAttrGroupSecond);
            }
            if (skuLevFlag > 2) {
                if (EmptyUtils.isNotEmpty(thirdGroupIdList) && thirdGroupIdList.size() > 0) {
                    welfareGoodsAttrGroupThird.setId(thirdGroupIdList.get(0));
                    groupIdMapOld.put(3, thirdGroupIdList.get(0));
                }
                welfareGoodsAttrGroupThird.setGroupName(welfareGoodsManageSkuAddDto0.getThirdGroupName());
                welfareGoodsAttrGroupThird.setCreateTime(new Date());
                welfareGoodsAttrGroupThird.setUpdateTime(new Date());
                welfareGoodsAttrGroupThird.setSort(3);
                welfareGoodsAttrGroupThird.setStatus(1);
                welfareGoodsAttrGroupList.add(welfareGoodsAttrGroupThird);
            }
            if (EmptyUtils.isNotEmpty(welfareGoodsAttrGroupList) && welfareGoodsAttrGroupList.size() > 0) {
                welfareGoodsAttrGroupService.insertGoodsAttrGroupList(welfareGoodsAttrGroupList);
            }
            System.out.println("groupIdMapOld: " + groupIdMapOld);
            // 保持原id插入以后的组id
            Map<Integer, Integer> groupIdMapNew = new HashMap<>();
            for (WelfareGoodsAttrGroup welfareGoodsAttrGroup : welfareGoodsAttrGroupList) {
                groupIdMapNew.put(welfareGoodsAttrGroup.getSort(), welfareGoodsAttrGroup.getId());
            }
            System.out.println("groupIdMapNew: " + groupIdMapNew);
            // 添加到商品规格组关联表
            List<WelfareGoodsAttrGroupRel> welfareGoodsAttrGroupRelList = new ArrayList<>();
            for (WelfareGoodsAttrGroup welfareGoodsAttrGroup : welfareGoodsAttrGroupList) {
                WelfareGoodsAttrGroupRel welfareGoodsAttrGroupRel = new WelfareGoodsAttrGroupRel();
                welfareGoodsAttrGroupRel.setGoodsId(welfareGoodsManageAddDto.getGoodsId());
                Integer sort = welfareGoodsAttrGroup.getSort();
                Integer groupId = getGroupIdFromOldBeforeBySort(groupIdMapOld, groupIdMapNew, sort);
                welfareGoodsAttrGroupRel.setGroupId(groupId);
                welfareGoodsAttrGroupRel.setLevel(sort);
                welfareGoodsAttrGroupRel.setCreateTime(new Date());
                welfareGoodsAttrGroupRel.setUpdateTime(new Date());
                welfareGoodsAttrGroupRel.setStatus(1);
                welfareGoodsAttrGroupRelList.add(welfareGoodsAttrGroupRel);
            }
            if (EmptyUtils.isNotEmpty(welfareGoodsAttrGroupRelList) && welfareGoodsAttrGroupRelList.size() > 0) {
                // 添加到商品规格组关联表
                welfareGoodsAttrGroupRelService.insertList(welfareGoodsAttrGroupRelList);
            }
            // 把规格以规格组id和规格值名为key、detailId为值放入到Map中
            Map<String, Integer> groupDetailIdMapOld = new HashMap<>();
            for (WelfareGoodsAttr welfareGoodsManageSkuAddDto : welfareGoodsManageAddDtoSkuList) {
                // 如果该属性组下面有值，纪录该规格值的id
                if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getFirstDetailId())) {
                    Integer groupId = getGroupIdFromOldBeforeBySort(groupIdMapOld, groupIdMapNew, 1);
                    String key = groupId + welfareGoodsManageSkuAddDto.getFirstDetailName();
                    groupDetailIdMapOld.put(key, welfareGoodsManageSkuAddDto.getFirstDetailId());
                }
                if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getSecondDetailId())) {
                    Integer groupId = getGroupIdFromOldBeforeBySort(groupIdMapOld, groupIdMapNew, 2);
                    String key = groupId + welfareGoodsManageSkuAddDto.getSecondDetailName();
                    groupDetailIdMapOld.put(key, welfareGoodsManageSkuAddDto.getSecondDetailId());
                }
                if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getThirdDetailId())) {
                    Integer groupId = getGroupIdFromOldBeforeBySort(groupIdMapOld, groupIdMapNew, 3);
                    String key = groupId + welfareGoodsManageSkuAddDto.getThirdDetailName();
                    groupDetailIdMapOld.put(key, welfareGoodsManageSkuAddDto.getThirdDetailId());
                }
            }
            System.out.println("groupDetailIdMapOld: " + groupDetailIdMapOld);
            // 对不同级别的规格值进行唯一过滤，添加不同级别规格值到detail表
            List<WelfareGoodsAttrDetail> welfareGoodsAttrDetailList = new ArrayList<>();
            // 一级规格值
            if (skuLevFlag > 0) {
                for (WelfareGoodsAttr welfareGoodsManageSkuAddDto : welfareGoodsManageAddDtoSkuListFirst) {
                    WelfareGoodsAttrDetail welfareGoodsAttrDetail = new WelfareGoodsAttrDetail();
                    welfareGoodsAttrDetail.setDetailName(welfareGoodsManageSkuAddDto.getFirstDetailName());
                    Integer groupId = getGroupIdFromOldBeforeBySort(groupIdMapOld, groupIdMapNew, 1);
                    welfareGoodsAttrDetail.setGroupId(groupId);
                    welfareGoodsAttrDetail.setCreateTime(new Date());
                    welfareGoodsAttrDetail.setSort(1);
                    welfareGoodsAttrDetail.setStatus(1);
                    welfareGoodsAttrDetail.setUpdateTime(new Date());
                    if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getFirstDetailId())) {
                        welfareGoodsAttrDetail.setId(welfareGoodsManageSkuAddDto.getFirstDetailId());
                    } else {
                        // 如果为空，去看一下该规格值是否存在，如果规格值存在，要设置id值为原属性值id
                        String key = groupId + welfareGoodsManageSkuAddDto.getFirstDetailName();
                        if (EmptyUtils.isNotEmpty(groupDetailIdMapOld.get(key))) {
                            welfareGoodsAttrDetail.setId(groupDetailIdMapOld.get(key));
                        }
                    }
                    welfareGoodsAttrDetailList.add(welfareGoodsAttrDetail);
                }
            }
            // 二级规格值
            if (skuLevFlag > 1) {
                for (WelfareGoodsAttr welfareGoodsManageSkuAddDto : welfareGoodsManageAddDtoSkuListSecond) {
                    WelfareGoodsAttrDetail welfareGoodsAttrDetail = new WelfareGoodsAttrDetail();
                    welfareGoodsAttrDetail.setDetailName(welfareGoodsManageSkuAddDto.getSecondDetailName());
                    Integer groupId = getGroupIdFromOldBeforeBySort(groupIdMapOld, groupIdMapNew, 2);
                    welfareGoodsAttrDetail.setGroupId(groupId);
                    welfareGoodsAttrDetail.setCreateTime(new Date());
                    welfareGoodsAttrDetail.setSort(2);
                    welfareGoodsAttrDetail.setStatus(1);
                    welfareGoodsAttrDetail.setUpdateTime(new Date());
                    if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getSecondDetailId())) {
                        welfareGoodsAttrDetail.setId(welfareGoodsManageSkuAddDto.getSecondDetailId());
                    } else {
                        // 如果为空，去看一下该规格值是否存在，如果规格值存在，要设置id值为原属性值id
                        String key = groupId + welfareGoodsManageSkuAddDto.getSecondDetailName();
                        if (EmptyUtils.isNotEmpty(groupDetailIdMapOld.get(key))) {
                            welfareGoodsAttrDetail.setId(groupDetailIdMapOld.get(key));
                        }
                    }
                    welfareGoodsAttrDetailList.add(welfareGoodsAttrDetail);
                }
            }
            // 三级规格值
            if (skuLevFlag > 2) {
                for (WelfareGoodsAttr welfareGoodsManageSkuAddDto : welfareGoodsManageAddDtoSkuListThird) {
                    WelfareGoodsAttrDetail welfareGoodsAttrDetail = new WelfareGoodsAttrDetail();
                    welfareGoodsAttrDetail.setDetailName(welfareGoodsManageSkuAddDto.getThirdDetailName());
                    Integer groupId = getGroupIdFromOldBeforeBySort(groupIdMapOld, groupIdMapNew, 3);
                    welfareGoodsAttrDetail.setGroupId(groupId);
                    welfareGoodsAttrDetail.setCreateTime(new Date());
                    welfareGoodsAttrDetail.setSort(3);
                    welfareGoodsAttrDetail.setStatus(1);
                    welfareGoodsAttrDetail.setUpdateTime(new Date());
                    if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getThirdDetailId())) {
                        welfareGoodsAttrDetail.setId(welfareGoodsManageSkuAddDto.getThirdDetailId());
                    } else {
                        // 如果为空，去看一下该规格值是否存在，如果规格值存在，要设置id值为原属性值id
                        String key = groupId + welfareGoodsManageSkuAddDto.getThirdDetailName();
                        if (EmptyUtils.isNotEmpty(groupDetailIdMapOld.get(key))) {
                            welfareGoodsAttrDetail.setId(groupDetailIdMapOld.get(key));
                        }
                    }
                    welfareGoodsAttrDetailList.add(welfareGoodsAttrDetail);
                }
            }
            welfareGoodsAttrDetailService.insertGoodsAttrDetailList(welfareGoodsAttrDetailList);// 保持原id插入
            Map<String, Integer> groupDetailIdMapNew = new HashMap<>();// 会存在生成新的规格值
            for (WelfareGoodsAttrDetail welfareGoodsAttrDetail : welfareGoodsAttrDetailList) {
                String key = welfareGoodsAttrDetail.getGroupId() + welfareGoodsAttrDetail.getDetailName();
                groupDetailIdMapNew.put(key, welfareGoodsAttrDetail.getId());
            }
            System.out.println("groupDetailIdMapNew: " + groupDetailIdMapNew);
            // 获取该商品下原来所有的sku（预占数据删除前拿出来，以skuId为key,lockQuantity为值放入到Map中）
            Example welfareGoodsAttrExampleGoods = new Example(WelfareGoodsAttr.class);
            welfareGoodsAttrExampleGoods.createCriteria().andEqualTo("goodsId", welfareGoodsManageAddDto.getGoodsId());
            List<WelfareGoodsAttr> welfareGoodsAttrListOld = welfareGoodsAttrService.selectByExample(welfareGoodsAttrExampleGoods);
            Map<Integer, Integer> skuLockQuantityMap = new HashMap<>();
            if (EmptyUtils.isNotEmpty(welfareGoodsAttrListOld)) {
                welfareGoodsAttrListOld.forEach(welfareGoodsAttr -> {
                    skuLockQuantityMap.put(welfareGoodsAttr.getId(), welfareGoodsAttr.getLockQuantity());
                });
            }
            // skuId不为空的（已有的不包含删除了的）
            List<Integer> oldSkuIdList = welfareGoodsManageAddDtoSkuList.stream().filter(s -> s.getId() != null && EmptyUtils.isNotEmpty(s.getId())).map(WelfareGoodsAttr::getId).collect(Collectors.toList());
            // 删除该goodsId下其他（未传过来需要删除）skuId
            if (EmptyUtils.isNotEmpty(oldSkuIdList)) {
                // 已有的进行物理删除
                welfareGoodsAttrService.deleteGoodsAttrSkuListBySkuId(oldSkuIdList);//物理删除
                // 匹配不到了的进行逻辑删除
                List<Integer> deleteLogicIdList = welfareGoodsAttrService.getGoodsAttrSkuListBySkuId(oldSkuIdList, welfareGoodsManageAddDto.getGoodsId());
                if (EmptyUtils.isNotEmpty(deleteLogicIdList)) {
                    welfareGoodsAttrService.deleteLogicGoodsAttrSkuListBySkuId(deleteLogicIdList);//逻辑删除
                }
            } else {
                // 如果全部组都没有规格id，更新商品下规格为软删除
                Example goodsAttrExample = new Example(WelfareGoodsAttr.class);
                goodsAttrExample.createCriteria().andEqualTo("goodsId", welfareGoodsManageAddDto.getGoodsId());
                WelfareGoodsAttr welfareGoodsAttrUpd = new WelfareGoodsAttr();
                welfareGoodsAttrUpd.setUpdateTime(new Date());
                welfareGoodsAttrUpd.setStatus(0);
                welfareGoodsAttrService.updateByExampleSelective(welfareGoodsAttrUpd, goodsAttrExample);
            }
            List<WelfareGoodsAttr> welfareGoodsAttrList = new ArrayList<>();
            for (int i = 0; i < welfareGoodsManageAddDtoSkuList.size(); i++) {
                WelfareGoodsAttr welfareGoodsManageSkuAddDto = welfareGoodsManageAddDtoSkuList.get(i);
                WelfareGoodsAttr welfareGoodsAttr = new WelfareGoodsAttr();
                // 设置skuId，如果这个skuId有，说明这个未改动，如果没有(为新增的)就自己生成
                if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getId())) {
                    welfareGoodsAttr.setId(welfareGoodsManageSkuAddDto.getId());
                    // 拿到map中以skuId为key的预占数量
                    welfareGoodsAttr.setLockQuantity(skuLockQuantityMap.get(welfareGoodsManageSkuAddDto.getId()));
                } else {
                    welfareGoodsAttr.setLockQuantity(0);
                }
                welfareGoodsAttr.setGoodsId(welfareGoodsManageAddDto.getGoodsId());
                // 设置一级规格信息
                if (skuLevFlag > 0) {
                    Integer groupId = getGroupIdFromOldBeforeBySort(groupIdMapOld, groupIdMapNew, 1);
                    welfareGoodsAttr.setFirstGroupId(groupId);
                    welfareGoodsAttr.setFirstGroupName(welfareGoodsManageSkuAddDto.getFirstGroupName());
                    welfareGoodsAttr.setFirstDetailName(welfareGoodsManageSkuAddDto.getFirstDetailName());
                    String key = groupId + welfareGoodsManageSkuAddDto.getFirstDetailName();
                    // 批量插入的id是自增分配，如果已有id获取到的id为自增分配的，所以先获取是否有个属性值id
                    Integer detailId;
                    if (EmptyUtils.isNotEmpty(groupDetailIdMapOld.get(key))) {
                        detailId = groupDetailIdMapOld.get(key);
                    } else {
                        detailId = groupDetailIdMapNew.get(key);
                    }
                    welfareGoodsAttr.setFirstDetailId(detailId);
                }
                // 设置二级规格信息
                if (skuLevFlag > 1) {
                    Integer groupId = getGroupIdFromOldBeforeBySort(groupIdMapOld, groupIdMapNew, 2);
                    welfareGoodsAttr.setSecondGroupId(groupId);
                    welfareGoodsAttr.setSecondGroupName(welfareGoodsManageSkuAddDto.getSecondGroupName());
                    welfareGoodsAttr.setSecondDetailName(welfareGoodsManageSkuAddDto.getSecondDetailName());
                    String key = groupId + welfareGoodsManageSkuAddDto.getSecondDetailName();
                    // 批量插入的id是自增分配，如果已有id获取到的id为自增分配的，所以先获取是否有个属性值id
                    Integer detailId;
                    if (EmptyUtils.isNotEmpty(groupDetailIdMapOld.get(key))) {
                        detailId = groupDetailIdMapOld.get(key);
                    } else {
                        detailId = groupDetailIdMapNew.get(key);
                    }
                    welfareGoodsAttr.setSecondDetailId(detailId);
                }
                // 设置三级规格信息
                if (skuLevFlag > 2) {
                    Integer groupId = getGroupIdFromOldBeforeBySort(groupIdMapOld, groupIdMapNew, 3);
                    welfareGoodsAttr.setThirdGroupId(groupId);
                    welfareGoodsAttr.setThirdGroupName(welfareGoodsManageSkuAddDto.getThirdGroupName());
                    welfareGoodsAttr.setThirdDetailName(welfareGoodsManageSkuAddDto.getThirdDetailName());
                    String key = groupId + welfareGoodsManageSkuAddDto.getThirdDetailName();
                    // 批量插入的id是自增分配，如果已有id获取到的id为自增分配的，所以先获取是否有个属性值id
                    Integer detailId;
                    if (EmptyUtils.isNotEmpty(groupDetailIdMapOld.get(key))) {
                        detailId = groupDetailIdMapOld.get(key);
                    } else {
                        detailId = groupDetailIdMapNew.get(key);
                    }
                    welfareGoodsAttr.setThirdDetailId(detailId);
                }
                // 设置价格、成本价格、库存或者卡密id
                if (welfareGoodsManageSkuAddDto.getPrice() == null) {
                    throw new CommonException("请填写价格信息");
                } else {
                    welfareGoodsAttr.setPrice(welfareGoodsManageSkuAddDto.getPrice());
                }
                if (welfareGoodsManageSkuAddDto.getCostPrice() == null) {
                    throw new CommonException("请填写成本价信息");
                } else {
                    welfareGoodsAttr.setCostPrice(welfareGoodsManageSkuAddDto.getCostPrice());
                }
                // 规格图片
                if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getSkuPic())) {
                    welfareGoodsAttr.setSkuPic(welfareGoodsManageSkuAddDto.getSkuPic());
                }
                //  修改时候实体商品库存数量以用户录入为主
                if (welfareGoodsManageAddDto.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_PHYSICAL.getCode())) {
                    if (welfareGoodsManageSkuAddDto.getQuantity() == null) {
                        throw new CommonException("请填写库存数量");
                    } else {
                        welfareGoodsAttr.setQuantity(welfareGoodsManageSkuAddDto.getQuantity());// 库存数量
                    }
                }
                // 虚拟商品库存为券密组上带过来的库存
                else if (welfareGoodsManageAddDto.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getCode())) {
                    if (EmptyUtils.isEmpty(welfareGoodsManageSkuAddDto.getAttrContactType())) {
                        throw new CommonException("请选择关联类型");
                    }
                    // 券密组类型需要选择券密组
                    if (welfareGoodsManageSkuAddDto.getAttrContactType().equals(WelfareGoodsEnum.GOODS_ATTR_TYPE_VIRTUAL_VOUCHER.getCode())) {
                        if (welfareGoodsManageSkuAddDto.getVoucherSecretGroupId() == null) {
                            throw new CommonException("请填写券密组信息（虚拟商品）");
                        }
                        if (welfareGoodsManageSkuAddDto.getVoucherSecretGroupId() > 0) {
                            // 虚拟商品库存数量从券密组获取
                            Example welfareGoodsAttrExampleCount = new Example(WelfareGoodsAttr.class);
                            if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getId())) {
                                welfareGoodsAttrExampleCount.createCriteria()
                                        .andEqualTo("status", 1)
                                        .andEqualTo("voucherSecretGroupId", welfareGoodsManageSkuAddDto.getVoucherSecretGroupId())
                                        .andNotEqualTo("id", welfareGoodsManageSkuAddDto.getId());
                            } else {
                                welfareGoodsAttrExampleCount.createCriteria()
                                        .andEqualTo("status", 1)
                                        .andEqualTo("voucherSecretGroupId", welfareGoodsManageSkuAddDto.getVoucherSecretGroupId());
                            }
                            Integer attrCount = welfareGoodsAttrService.selectCountByExample(welfareGoodsAttrExampleCount);
                            if (attrCount > 0) {
                                throw new CommonException("券密组已被绑定");
                            }
                            // 虚拟商品绑定券密组，库存数量为券密组未被兑换的数量
                            VoucherSecretGroupSellVo voucherSecretGroupSellVo = welfareVoucherSecretGroupService.getVoucherSecretGroupWithSellInfo(welfareGoodsManageSkuAddDto.getVoucherSecretGroupId());
                            if (EmptyUtils.isNotEmpty(voucherSecretGroupSellVo) && EmptyUtils.isNotEmpty(voucherSecretGroupSellVo.getCountIsNotSell())) {
                                welfareGoodsAttr.setQuantity(voucherSecretGroupSellVo.getCountIsNotSell());
                            } else {
                                throw new CommonException("券密组已失效");
                            }
                        }
                        welfareGoodsAttr.setVoucherSecretGroupId(welfareGoodsManageSkuAddDto.getVoucherSecretGroupId());
                        if (welfareGoodsManageSkuAddDto.getVoucherSecretGroupId().equals(0)) {
                            welfareGoodsAttr.setQuantity(0);
                        }
                    }
                    // 充值类型需要选择产品编码及产品名
                    else if (welfareGoodsManageSkuAddDto.getAttrContactType().equals(WelfareGoodsEnum.GOODS_ATTR_TYPE_VIRTUAL_RECHARGE.getCode())) {
                        if (EmptyUtils.isNotEmpty(welfareGoodsManageSkuAddDto.getProductName())) {
                            welfareGoodsAttr.setProductName(welfareGoodsManageSkuAddDto.getProductName());
                        }
                        if (EmptyUtils.isEmpty(welfareGoodsManageSkuAddDto.getProductId())) {
                            throw new CommonException("请填写券密组信息（虚拟商品）");
                        } else {
                            welfareGoodsAttr.setProductId(welfareGoodsManageSkuAddDto.getProductId());
                        }
                        welfareGoodsAttr.setAttrContactType(welfareGoodsManageSkuAddDto.getAttrContactType());
                    } else {
                        throw new CommonException("无效的关联类型");
                    }
                } else {
                    if(EmptyUtils.isEmpty(welfareGoodsManageAddDto.getIsJicai())){
                        throw new CommonException("无效的商品类型");
                    }
                }
                welfareGoodsAttr.setCreateTime(new Date());
                welfareGoodsAttr.setUpdateTime(new Date());
                welfareGoodsAttr.setStatus(1);
                welfareGoodsAttr.setSort(i + 1);
                welfareGoodsAttrList.add(welfareGoodsAttr);
            }
            System.out.println("welfareGoodsAttrList: " + welfareGoodsAttrList.toString());
            welfareGoodsAttrService.insertGoodsAttrSkuList(welfareGoodsAttrList);
        } else {
            // 如果skuId列表为空，软删商品下所有的规格
            Example example = new Example(WelfareGoodsAttr.class);
            example.createCriteria().andEqualTo("goodsId", welfareGoodsManageAddDto.getGoodsId());
            WelfareGoodsAttr welfareGoodsAttrUpd = new WelfareGoodsAttr();
            welfareGoodsAttrUpd.setStatus(0);
            welfareGoodsAttrService.updateByExampleSelective(welfareGoodsAttrUpd, example);
        }
        // 商品图片修改
        // 先删除该商品下的所有img，然后新增
        WelfareGoodsImg welfareGoodsImgDel = new WelfareGoodsImg();
        welfareGoodsImgDel.setGoodsId(welfareGoodsManageAddDto.getGoodsId());
        welfareGoodsImgService.delete(welfareGoodsImgDel);
        if (EmptyUtils.isNotEmpty(welfareGoodsManageAddDto.getImgList())) {
            for (WelfareGoodsImg welfareGoodsImg : welfareGoodsManageAddDto.getImgList()) {
                welfareGoodsImg.setGoodsId(welfareGoodsManageAddDto.getGoodsId());
                welfareGoodsImg.setCreateTime(new Date());
                welfareGoodsImg.setStatus(1);
            }
            welfareGoodsImgService.insertList(welfareGoodsManageAddDto.getImgList());
        }
        // 先删除原品类列表
        Example example = new Example(WelfareGoodsLabelRel.class);
        example.createCriteria().andEqualTo("goodsId", welfareGoodsManageAddDto.getGoodsId());
        welfareGoodsCategoryRelService.deleteByExample(example);
        // 修改商品品类信息
        List<Integer> categoryIdList = welfareGoodsManageAddDto.getCategoryIdList();
        if (EmptyUtils.isNotEmpty(categoryIdList) && categoryIdList.size() > 0) {
            // 再更新新的品类
            List<WelfareGoodsCategoryRel> welfareGoodsCategoryRelList = new ArrayList<>();
            for (Integer categoryId : categoryIdList) {
                WelfareGoodsCategoryRel welfareGoodsCategoryRelAdd = new WelfareGoodsCategoryRel();
                welfareGoodsCategoryRelAdd.setGoodsId(welfareGoodsManageAddDto.getGoodsId());
                welfareGoodsCategoryRelAdd.setCategoryId(categoryId);
                welfareGoodsCategoryRelList.add(welfareGoodsCategoryRelAdd);
            }
            welfareGoodsCategoryRelService.insertList(welfareGoodsCategoryRelList);
        }
        // 商品供应商修改
        // 先删除该商品下的所有供应商，然后新增
        WelfareGoodsSupplier welfareGoodsSupplierDel = new WelfareGoodsSupplier();
        welfareGoodsSupplierDel.setGoodsId(welfareGoodsManageAddDto.getGoodsId());
        welfareGoodsSupplierService.delete(welfareGoodsSupplierDel);
        if (EmptyUtils.isNotEmpty(welfareGoodsManageAddDto.getSupplierList())) {
            for (WelfareGoodsSupplier welfareGoodsSupplier : welfareGoodsManageAddDto.getSupplierList()) {
                welfareGoodsSupplier.setGoodsId(welfareGoodsManageAddDto.getGoodsId());
                welfareGoodsSupplier.setCreateTime(new Date());
                welfareGoodsSupplier.setStatus(1);
            }
            welfareGoodsSupplierService.insertList(welfareGoodsManageAddDto.getSupplierList());
        }
        //如果是上架非集采商品，则需要同步商品到企业端
        if(welfareGoodsManageAddDto.getOptType().equals(WelfareGoodsEnum.GOODS_OPT_TYPE_SHELVES.getCode()) && EmptyUtils.isEmpty(welfareGoodsManageAddDto.getIsJicai())){
            resMap.put("goodsId", welfareGoodsManageAddDto.getGoodsId());
        }
        resMap.put("code", 1);
        resMap.put("msg", "success");
        return resMap;
    }

    /******
     * 判断是否包含供应商或品牌
     * @param supplierVos 现已有供应商以及其包含的品牌
     * @param supplierName 供应商名称
     * @param brandName 品牌名称
     * @return
     */
    private String containItem(List<WelfareSupplierVo> supplierVos, String supplierName, String brandName){
        String res = "0";
        if(EmptyUtils.isNotEmpty(supplierVos)){
            for (WelfareSupplierVo x:supplierVos) {
                if(x.getName().equals(supplierName)){
                    if(EmptyUtils.isNotEmpty(x.getBrandList())){
                        for (WelfareBrand y:x.getBrandList()) {
                            if(y.getName().equals(brandName)){
                                res = x.getId()+"_"+y.getId();
                                break;
                            }
                        };
                    }
                }
            }
        }
        return res;
    }

    @Override
    public Integer importJicaiGoodsList(List<List<String>> list, LoginSysAdminVo adminInfo) {
        if (EmptyUtils.isEmpty(list)) {
            throw new CommonException("请填写导入集采商品信息");
        }
        if (list.size() > 1000) {
            throw new CommonException("超过导入条数限制:1000");
        }
        //查所有供应商
        List<WelfareSupplierVo> supplierVos = new ArrayList<>();
        WelfareSupplier welfareSupplier = new WelfareSupplier();
        welfareSupplier.setStatus(CommonConstants.YES);
        List<WelfareSupplier> supplierList = welfareSupplierService.select(welfareSupplier);
        supplierList.forEach(x->{
            WelfareSupplierVo supplierVo = new WelfareSupplierVo();
            supplierVo.setId(x.getId());
            supplierVo.setName(x.getName());
            List<WelfareBrand> brandList = welfareSupplierBrandService.selectBrandListBySupplierId(x.getId());
            supplierVo.setBrandList(brandList);
            supplierVos.add(supplierVo);
        });
        int result = 0;//新增条数
        List<WelfareGoods> welfareGoodsList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            List<String> item = list.get(i);
            /*if (EmptyUtils.isEmpty(item.get(0))) {
                throw new CommonException("商品图片地址不能为空");
            }*/
            if (EmptyUtils.isNotEmpty(item.get(0)) && item.get(1).length() > 128) {
                throw new CommonException("商品图片地址长度应在128个字符内");
            }
            if (EmptyUtils.isEmpty(item.get(1))) {
                throw new CommonException("商品名称不能为空");
            }
            if (item.get(1).length() > 100) {
                throw new CommonException("商品名称长度应在100个字符内");
            }
            if (EmptyUtils.isEmpty(item.get(2))) {
                throw new CommonException("商品品牌不能为空");
            }
            if (item.get(2).length() > 20) {
                throw new CommonException("商品品牌名称长度应在20个字符内");
            }
            if (EmptyUtils.isEmpty(item.get(3))) {
                throw new CommonException("商品市场价格不能为空");
            }
            if (!NumberUtils.isNumber(item.get(3))) {
                throw new CommonException("商品市场价格式不正确：" + item.get(3));
            }
            if (EmptyUtils.isEmpty(item.get(4))) {
                throw new CommonException("供应商名称不能为空");
            }
            if (item.get(4).length() > 50) {
                throw new CommonException("供应商名称长度应在50个字符内");
            }
            if (EmptyUtils.isEmpty(item.get(5))) {
                throw new CommonException("商品供应价格不能为空");
            }
            if (!NumberUtils.isNumber(item.get(5))) {
                throw new CommonException("商品供应价格式不正确：" + item.get(5));
            }
            String containItemResult = containItem(supplierVos,item.get(4),item.get(2));
            if(!containItemResult.equals("0")){
                WelfareGoods welfareGoods = new WelfareGoods();
                welfareGoods.setGoodsName(item.get(1));
                welfareGoods.setGoodsImg(ALiYunOSSConstant.WELFARE_IMG_CENTRE +item.get(0));
                welfareGoods.setBrandId(Integer.valueOf(containItemResult.split("_")[1]));
                welfareGoods.setSupplierId(Integer.valueOf(containItemResult.split("_")[0]));
                welfareGoods.setMarketPrice(new BigDecimal(item.get(3)));
                //welfareGoods.setGoodsName(item.get(4));
                welfareGoods.setCreditsAmount(new BigDecimal(item.get(5)));
                welfareGoods.setIsJicai(CommonConstants.YES);
                welfareGoods.setGoodsStatus(WelfareGoodsEnum.GOODS_STATUS_TYPE_SHELVES.getCode());
                welfareGoods.setGoodsType(9);
                welfareGoods.setPartitionId(-1);
                welfareGoods.setFirstClassifyId(-1);
                welfareGoods.setSecondClassifyId(-1);
                welfareGoods.setThirdClassifyId(-1);
                welfareGoods.setGoodsDetail("集采商品详情");
                welfareGoods.setStatus(CommonConstants.YES);
                welfareGoods.setCreater(adminInfo.getId());
                welfareGoods.setCreaterName(adminInfo.getUserName());
                welfareGoods.setCreateTime(new Date());
                welfareGoodsList.add(welfareGoods);
            }
        }
        if(EmptyUtils.isNotEmpty(welfareGoodsList)){
            welfareGoodsMapper.insertList(welfareGoodsList);
            //商品供应商关联
            List<WelfareGoodsSupplier> welfareGoodsSupplierList = new ArrayList<>();
            welfareGoodsList.forEach(x->{
                WelfareGoodsSupplier welfareGoodsSupplier = new WelfareGoodsSupplier();
                welfareGoodsSupplier.setGoodsId(x.getId());
                welfareGoodsSupplier.setSupplierId(x.getSupplierId());
                welfareGoodsSupplier.setStatus(CommonConstants.YES);
                welfareGoodsSupplier.setSupplyPrice(x.getCreditsAmount());
                welfareGoodsSupplier.setCreateTime(new Date());
                welfareGoodsSupplierList.add(welfareGoodsSupplier);
            });
            welfareGoodsSupplierService.insertList(welfareGoodsSupplierList);
            //商品图片
            List<WelfareGoodsImg> welfareGoodsImgList = new ArrayList<>();
            welfareGoodsList.forEach(x->{
                if(EmptyUtils.isNotEmpty(x.getGoodsImg())){
                    WelfareGoodsImg welfareGoodsImg = new WelfareGoodsImg();
                    welfareGoodsImg.setGoodsId(x.getId());
                    welfareGoodsImg.setImg(x.getGoodsImg());
                    welfareGoodsImg.setStatus(CommonConstants.YES);
                    welfareGoodsImg.setSort(0);
                    welfareGoodsImg.setCreateTime(new Date());
                    welfareGoodsImgList.add(welfareGoodsImg);
                }
            });
            if(EmptyUtils.isNotEmpty(welfareGoodsImgList)){
                welfareGoodsImgService.insertList(welfareGoodsImgList);
            }
            result = welfareGoodsList.size();
        }
        return result;
    }

    @Override
    public PageInfo<WelfareGoodsBaseVo> getGoodsBaseListPage(WelfareGoodsPageQuery query) {
        PageHelper.startPage(query);
        List<WelfareGoodsBaseVo> welfareGoodsWithLowPriceVoList = welfareGoodsMapper.selectGoodsListBase(query);
        if (EmptyUtils.isNotEmpty(welfareGoodsWithLowPriceVoList)) {
            welfareGoodsWithLowPriceVoList.forEach(welfareGoodsWithLowPriceVo -> {
                if (EmptyUtils.isNotEmpty(welfareGoodsWithLowPriceVo.getGoodsImg())) {
                    welfareGoodsWithLowPriceVo.setGoodsImg(ImageUtils.setImageSrc(welfareGoodsWithLowPriceVo.getGoodsImg()));
                }
            });
        }
        PageInfo<WelfareGoodsBaseVo> page = new PageInfo<WelfareGoodsBaseVo>(welfareGoodsWithLowPriceVoList);
        return page;
    }

    @Override
    public PageInfo<WelfareGoodsBaseVo> getGoodsListPageByMicroId(WelfareGoodsPageQuery query) {
        PageHelper.startPage(query);
        List<WelfareGoodsBaseVo> welfareGoodsWithLowPriceVoList = welfareGoodsMapper.selectGoodsLinkByMicroId(query);
        if (EmptyUtils.isNotEmpty(welfareGoodsWithLowPriceVoList)) {
            welfareGoodsWithLowPriceVoList.forEach(welfareGoodsWithLowPriceVo -> {
                if (EmptyUtils.isNotEmpty(welfareGoodsWithLowPriceVo.getGoodsImg())) {
                    welfareGoodsWithLowPriceVo.setGoodsImg(ImageUtils.setImageSrc(welfareGoodsWithLowPriceVo.getGoodsImg()));
                }
            });
        }
        PageInfo<WelfareGoodsBaseVo> page = new PageInfo<WelfareGoodsBaseVo>(welfareGoodsWithLowPriceVoList);
        return page;
    }


    @Override
    public WelfareMovieInfo getGoodsLinkByMicroIdForMovie(Integer microId) {
        //PageHelper.startPage(query);
        WelfareMovieInfo movieInfo = welfareGoodsMapper.getGoodsLinkByMicroIdForMovie(microId);
        if (EmptyUtils.isNotEmpty(movieInfo)) {
            movieInfo.setLogo(ImageUtils.setImageSrc(movieInfo.getLogo()));
        }
        return movieInfo;
    }

    @Override
    public List<WelfareBrand> getBrandListByGoodsQuery(WelfareGoodsPageQuery welfareGoodsQuery) {
        List<WelfareBrand> welfareBrandList = welfareGoodsMapper.getBrandListByGoodsQuery(welfareGoodsQuery);
        if (EmptyUtils.isNotEmpty(welfareBrandList)) {
            welfareBrandList.forEach(welfareBrand -> {
                if (EmptyUtils.isNotEmpty(welfareBrand.getImg())) {
                    welfareBrand.setImg(ImageUtils.setImageSrc(welfareBrand.getImg()));
                }
            });
        }
        return welfareBrandList;
    }

    @Override
    public List<Integer> getGoodsThirdClassifyIdsByPartitions(List<Integer> partitionIdList) {
        return welfareGoodsMapper.getGoodsThirdClassifyIdsByPartitions(partitionIdList);
    }

    @Override
    public boolean validGoodsSupplierDelivery(WelfareGoodsDevAreaQuery query) {
        WelfareGoodsDetailVo goodsWithRestrictedAreasVo = welfareGoodsMapper.selectGoodsInfoDetailById(query.getGoodsId());
        if (EmptyUtils.isNotEmpty(goodsWithRestrictedAreasVo) && EmptyUtils.isNotEmpty(goodsWithRestrictedAreasVo.getRestrictedAreas())) {
            String[] restrictedAreasArray = goodsWithRestrictedAreasVo.getRestrictedAreas().split(",");
            if (restrictedAreasArray.length > 0) {
                for (int i = 0; i < restrictedAreasArray.length; i++) {
                    if (query.getArea().equals(restrictedAreasArray[i])){
                        return false;
                    }
                }
            }
        }
        return true;
    }

    @Override
    public List<WelfareGoodsAttr> getWelfareGoodsAttr(Integer goodsId) {
        WelfareGoodsAttr welfareGoodsAttrSelect = new WelfareGoodsAttr();
        welfareGoodsAttrSelect.setStatus(1);
        welfareGoodsAttrSelect.setGoodsId(goodsId);
        List<WelfareGoodsAttr> welfareGoodsAttrList = welfareGoodsAttrService.select(welfareGoodsAttrSelect);
        if (EmptyUtils.isNotEmpty(welfareGoodsAttrList)) {
            welfareGoodsAttrList.forEach(welfareGoodsAttr1 -> {
                if (EmptyUtils.isNotEmpty(welfareGoodsAttr1.getSkuPic())) {
                    welfareGoodsAttr1.setSkuPic(ImageUtils.setImageSrc(welfareGoodsAttr1.getSkuPic()));
                }
                if (EmptyUtils.isNotEmpty(welfareGoodsAttr1.getLockQuantity()) && EmptyUtils.isNotEmpty(welfareGoodsAttr1.getQuantity())) {
                    // 小程序端库存减去预占数量展示
                    Integer quantity = welfareGoodsAttr1.getQuantity() - welfareGoodsAttr1.getLockQuantity();
                    if (quantity > 0) {
                        welfareGoodsAttr1.setQuantity(quantity);
                    } else {
                        welfareGoodsAttr1.setQuantity(0);
                    }
                }
            });
        }
        return welfareGoodsAttrList;
    }

    @Override
    public List<WelfareGoodsAttr> getWelfareGoodsAttrNoCutLockQuantity(Integer goodsId) {
        WelfareGoodsAttr welfareGoodsAttrSelect = new WelfareGoodsAttr();
        welfareGoodsAttrSelect.setStatus(1);
        welfareGoodsAttrSelect.setGoodsId(goodsId);
        List<WelfareGoodsAttr> welfareGoodsAttrList = welfareGoodsAttrService.select(welfareGoodsAttrSelect);
        if (EmptyUtils.isNotEmpty(welfareGoodsAttrList)) {
            welfareGoodsAttrList.forEach(welfareGoodsAttr1 -> {
                if (EmptyUtils.isNotEmpty(welfareGoodsAttr1.getSkuPic())) {
                    welfareGoodsAttr1.setSkuPic(ImageUtils.setImageSrc(welfareGoodsAttr1.getSkuPic()));
                }
                if (EmptyUtils.isNotEmpty(welfareGoodsAttr1.getQuantity())) {
                    welfareGoodsAttr1.setQuantity(welfareGoodsAttr1.getQuantity() > 0 ? welfareGoodsAttr1.getQuantity() : 0);
                } else {
                    throw new CommonException("数据错误！");
                }
            });
        }
        return welfareGoodsAttrList;
    }

    @Override
    public List<WelfareSkuGoodsVo> getWelfareGoodsAttrVo(Integer goodsId) {
        WelfareGoodsAttr welfareGoodsAttrSelect = new WelfareGoodsAttr();
        welfareGoodsAttrSelect.setStatus(1);
        welfareGoodsAttrSelect.setGoodsId(goodsId);
        List<WelfareGoodsAttr> welfareGoodsAttrList = welfareGoodsAttrService.select(welfareGoodsAttrSelect);
        welfareGoodsAttrList = welfareGoodsAttrList.stream().sorted(Comparator.comparing(WelfareGoodsAttr::getSort)).collect(Collectors.toList());
        List<WelfareSkuGoodsVo> welfareGoodsAttrVos = new ArrayList<>();
        if (EmptyUtils.isNotEmpty(welfareGoodsAttrList)) {
            welfareGoodsAttrList.forEach(x -> {
                if (EmptyUtils.isNotEmpty(x.getSkuPic())) {
                    x.setSkuPic(ImageUtils.setImageSrc(x.getSkuPic()));
                }
                if (EmptyUtils.isNotEmpty(x.getLockQuantity()) && EmptyUtils.isNotEmpty(x.getQuantity())) {
                    x.setQuantity(x.getQuantity() - x.getLockQuantity());
                }
                WelfareSkuGoodsVo vo = new WelfareSkuGoodsVo();
                BeanUtils.copyProperties(x, vo);
                welfareGoodsAttrVos.add(vo);
                vo.setProfit(EmptyUtils.isEmpty(x.getPrice()) ? BigDecimal.ZERO : x.getPrice().subtract(x.getCostPrice()).divide(x.getPrice(), 6, 2).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
            });
        }
        return welfareGoodsAttrVos;
    }

    @Override
    public Integer updateGoodsBatchManage(WelfareGoodsBatchUpdateDto dto) {
        int result = 0 ;
        String[] ids_ = dto.getIds().split(",");
        StringBuffer goodsIdsBuf = new StringBuffer();
        for(int i=0;i<ids_.length;i++){
            String[] item = ids_[i].split("_");
            Integer goodsId = Integer.valueOf(item[0]);
            Integer platformId = Integer.valueOf(item[1]);
            Integer goodsStatus = Integer.valueOf(item[2]);
            Integer goodsType = Integer.valueOf(item[3]);
            //若是导入的平台商品，则判断同步商品状态
            if(platformId>0){
                WelfareGoods welfareGoods = welfareGoodsMapper.selectByPrimaryKey(platformId);
                if(welfareGoods.getGoodsStatus()!=WelfareGoodsEnum.GOODS_STATUS_TYPE_SHELVES.getCode()){
                    goodsStatus = WelfareGoodsEnum.GOODS_STATUS_TYPE_DOWN_PLATFORM.getCode();
                }
            }
            if(dto.getGoodsStatus()==WelfareGoodsEnum.GOODS_STATUS_TYPE_SHELVES.getCode()){
                if(goodsStatus==WelfareGoodsEnum.GOODS_STATUS_TYPE_SHELVES.getCode()){
                    throw new CommonException("操作失败，请检查商品状态：只能选择非上架状态的商品");
                }
            }else if(dto.getGoodsStatus()==WelfareGoodsEnum.GOODS_STATUS_TYPE_DOWN.getCode()){
                if(goodsStatus==WelfareGoodsEnum.GOODS_STATUS_TYPE_DOWN.getCode()){
                    throw new CommonException("操作失败，请检查商品状态：只能选择非下架状态的商品");
                }
            }
            goodsIdsBuf.append(goodsId).append(",");
        }
        if(EmptyUtils.isNotEmpty(goodsIdsBuf.toString())){
            dto.setIds(goodsIdsBuf.substring(0,goodsIdsBuf.length()-1));
            result += welfareGoodsMapper.batchUpdateGoods(dto);
            for (String id_:dto.getIds().split(",")) {
                WelfareGoods welfareGoods = welfareGoodsMapper.selectByPrimaryKey(Integer.valueOf(id_));
                if (EmptyUtils.isNotEmpty(welfareGoods)) {
                    String goodsOldStatus = "上架";
                    if(welfareGoods.getGoodsStatus()==WelfareGoodsEnum.GOODS_STATUS_TYPE_DOWN.getCode()){
                        goodsOldStatus = "下架";
                    }else if(welfareGoods.getGoodsStatus()==WelfareGoodsEnum.GOODS_STATUS_TYPE_DRAFT.getCode()){
                        goodsOldStatus = "草稿";
                    }
                    if(dto.getGoodsStatus() == WelfareGoodsEnum.GOODS_STATUS_TYPE_SHELVES.getCode()){//上架
                        operationLogService.saveOperationLog(welfareGoods.getId(),"批量修改商品["+welfareGoods.getGoodsName()+"]状态由"+goodsOldStatus+"变成上架", OperationConstant.TypeEnum.GOODS_UPDATE_STATUS_TO_SHELVES.getType(),dto.getUpdater(),dto.getUpdaterName());
                    }else if(dto.getGoodsStatus() == WelfareGoodsEnum.GOODS_STATUS_TYPE_DOWN.getCode()){//下架
                        operationLogService.saveOperationLog(welfareGoods.getId(),"批量修改商品["+welfareGoods.getGoodsName()+"]状态由"+goodsOldStatus+"变成下架",OperationConstant.TypeEnum.GOODS_UPDATE_STATUS_TO_DOWN.getType(),dto.getUpdater(),dto.getUpdaterName());
                    }
                }
            }
        }
        return result;
    }

    @Override
    public Integer updateGoodsPartitonBatch(WelfareGoodsBatchUpdateDto dto) {
        String[] ids_ = dto.getIds().split(",");
        StringBuffer goodsIdsBuf = new StringBuffer();
        for(int i=0;i<ids_.length;i++){
            String[] item = ids_[i].split("_");
            Integer goodsId = Integer.valueOf(item[0]);
            Integer platformId = Integer.valueOf(item[1]);
            Integer goodsStatus = Integer.valueOf(item[2]);
            Integer goodsType = Integer.valueOf(item[3]);
            goodsIdsBuf.append(goodsId).append(",");
        }
        if(EmptyUtils.isNotEmpty(goodsIdsBuf.toString())){
            dto.setIds(goodsIdsBuf.substring(0,goodsIdsBuf.length()-1));
            welfareGoodsMapper.batchUpdateGoods(dto);
        }
        return ids_.length;
    }

    @Override
    public Integer updateGoodsClassifyBatch(WelfareGoodsBatchUpdateDto dto) {
        String[] ids_ = dto.getIds().split(",");
        StringBuffer goodsIdsBuf = new StringBuffer();
        for(int i=0;i<ids_.length;i++){
            String[] item = ids_[i].split("_");
            Integer goodsId = Integer.valueOf(item[0]);
            Integer platformId = Integer.valueOf(item[1]);
            Integer goodsStatus = Integer.valueOf(item[2]);
            Integer goodsType = Integer.valueOf(item[3]);
            goodsIdsBuf.append(goodsId).append(",");
        }
        if(EmptyUtils.isNotEmpty(goodsIdsBuf.toString())){
            dto.setIds(goodsIdsBuf.substring(0,goodsIdsBuf.length()-1));
            welfareGoodsMapper.batchUpdateGoods(dto);
        }
        return ids_.length;
    }

    @Override
    public Integer updateGoodsSupplierBatch(WelfareGoodsBatchUpdateDto dto) {
        return welfareGoodsMapper.batchUpdateGoods(dto);
    }

    /**
     * 参数校验，商品对象组拼方法
     * @param resMap                   返回map
     * @param welfareGoodsManageAddDto 入参dto
     * @param welfareGoods             商品对象
     * @return boolean
     * @author ChenLong
     * @date 2021-06-01 11:30:22
     **/
    private boolean validGoodsManageAndBuildParams(Map<String, Object> resMap, WelfareGoodsManageAddDto welfareGoodsManageAddDto, WelfareGoods welfareGoods) {
        // 上架或者保存为草稿
        if (welfareGoodsManageAddDto.getOptType() == null) {
            resMap.put("code", 1900);
            resMap.put("msg", "无效的操作类型");
            return true;
        } else {
            // 不是草稿也不是上架
            if (!welfareGoodsManageAddDto.getOptType().equals(WelfareGoodsEnum.GOODS_OPT_TYPE_DRAFT.getCode()) && !welfareGoodsManageAddDto.getOptType().equals(WelfareGoodsEnum.GOODS_OPT_TYPE_SHELVES.getCode()) && !welfareGoodsManageAddDto.getOptType().equals(WelfareGoodsEnum.GOODS_OPT_TYPE_DOWN.getCode())) {
                resMap.put("code", 1900);
                resMap.put("msg", "无效的操作类型");
                return true;
            } else {
                welfareGoods.setGoodsStatus(welfareGoodsManageAddDto.getOptType());
            }
        }
        if (!welfareGoodsManageAddDto.getOptType().equals(WelfareGoodsEnum.GOODS_OPT_TYPE_DRAFT.getCode())) {
            // 商品基本属性
            if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getGoodsName())) {
                resMap.put("code", 1901);
                resMap.put("msg", "请填写商品名");
                return true;
            }
            /*if (welfareGoodsManageAddDto.getSort() == null) {
                resMap.put("code", 1902);
                resMap.put("msg", "请填写排序信息");
                return true;
            }*/
            /*if (welfareGoodsManageAddDto.getPartitionId() == null) {
                resMap.put("code", 1903);
                resMap.put("msg", "请填写分区");
                return true;
            }*/
            if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getSupplierId())) {
                resMap.put("code", 1904);
                resMap.put("msg", "请填写供应商");
                return true;
            }
            if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getBrandId())) {
                resMap.put("code", 1905);
                resMap.put("msg", "请填写品牌");
                return true;
            }
            if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getGoodsType())) {
                resMap.put("code", 1906);
                resMap.put("msg", "请填写商品类型");
                return true;
            }
            if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getFirstClassifyId())) {
                resMap.put("code", 1907);
                resMap.put("msg", "请填写一级分类");
                return true;
            }
            if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getSecondClassifyId())) {
                resMap.put("code", 1908);
                resMap.put("msg", "请填写二级分类");
                return true;
            }
            if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getThirdClassifyId())) {
                resMap.put("code", 1909);
                resMap.put("msg", "请填写三级分类");
                return true;
            }
            if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getIsJicai()) && EmptyUtils.isEmpty(welfareGoodsManageAddDto.getImgList())) {
                resMap.put("code", 1910);
                resMap.put("msg", "请上传商品图片");
                return true;
            }
            if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getSkuList()) && EmptyUtils.isEmpty(welfareGoodsManageAddDto.getIsJicai())) {
                resMap.put("code", 1911);
                resMap.put("msg", "请填写规格信息");
                return true;
            }
            if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getGoodsDetail())) {
                resMap.put("code", 1912);
                resMap.put("msg", "请填写商品详情");
                return true;
            }
            if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getIsJicai()) && EmptyUtils.isEmpty(welfareGoodsManageAddDto.getGoodsImg())) {
                resMap.put("code", 1913);
                resMap.put("msg", "请上传商品图片");
                return true;
            }
            // 非草稿箱的给上下架时间
            welfareGoods.setUpdateTime(new Date());

            // 如果是虚拟商品，考虑购买限制类型和购买限制数量
            if (welfareGoodsManageAddDto.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getCode())) {
                if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getBuyLimitType()) || welfareGoodsManageAddDto.getBuyLimit() == null) {
                    resMap.put("code", 1915);
                    resMap.put("msg", "请填写购买限制（虚拟商品）");
                    return true;
                }
                WelfareGoods welfareGoodsRes = welfareGoodsMapper.selectByPrimaryKey(welfareGoodsManageAddDto.getGoodsId());
                if (EmptyUtils.isNotEmpty(welfareGoodsRes)){
                    // 如果购买限制为卡购买限制，则比较限制数量
                    if (welfareGoodsManageAddDto.getBuyLimitType().equals(2)){
                        // 比较限制数量
                        if (!welfareGoodsManageAddDto.getBuyLimit().equals(welfareGoodsRes.getBuyLimit())){
                            // 原购买限制改动
                            if (welfareGoodsManageAddDto.getBuyLimit().equals(0) && welfareGoodsRes.getBuyLimit().equals(GOODS_BUY_LIMIT)){
                            } else {
                                WelfareGoodsModifyRecord welfareGoodsModifyRecord = new WelfareGoodsModifyRecord();
                                welfareGoodsModifyRecord.setGoodsId(welfareGoodsManageAddDto.getGoodsId());
                                // 原购买限制次数不为0，现在设置购买次数为0
                                if (welfareGoodsManageAddDto.getBuyLimit().equals(0)){
                                    welfareGoodsModifyRecord.setBuyLimit(0);
                                } else {
                                    welfareGoodsModifyRecord.setBuyLimit(welfareGoodsManageAddDto.getBuyLimit());
                                }
                                welfareGoodsModifyRecord.setBuyLimitOld(welfareGoodsRes.getBuyLimit());
                                welfareGoodsModifyRecord.setBuyLimitType(welfareGoodsManageAddDto.getBuyLimitType());
                                welfareGoodsModifyRecord.setBuyLimitTypeOld(welfareGoodsRes.getBuyLimitType());
                                welfareGoodsModifyRecord.setCreateTime(new Date());
                                welfareGoodsModifyRecordService.insert(welfareGoodsModifyRecord);
                            }
                        }
                    } else {
                        // 如果购买限制为次购买限制，原购买限制为卡购买限制
                        if (!welfareGoodsRes.getBuyLimitType().equals(welfareGoodsManageAddDto.getBuyLimitType())){
                            WelfareGoodsModifyRecord welfareGoodsModifyRecord = new WelfareGoodsModifyRecord();
                            welfareGoodsModifyRecord.setGoodsId(welfareGoodsManageAddDto.getGoodsId());
                            welfareGoodsModifyRecord.setBuyLimit(0);
                            welfareGoodsModifyRecord.setBuyLimitOld(welfareGoodsRes.getBuyLimit());
                            welfareGoodsModifyRecord.setBuyLimitType(welfareGoodsManageAddDto.getBuyLimitType());
                            welfareGoodsModifyRecord.setBuyLimitTypeOld(welfareGoodsRes.getBuyLimitType());
                            welfareGoodsModifyRecord.setCreateTime(new Date());
                            welfareGoodsModifyRecordService.insert(welfareGoodsModifyRecord);
                        }
                    }
                }
            }
        }

        welfareGoods.setGoodsName(welfareGoodsManageAddDto.getGoodsName());
        welfareGoods.setSort(9999);
        welfareGoods.setPartitionId(welfareGoodsManageAddDto.getPartitionId());
        welfareGoods.setSupplierId(welfareGoodsManageAddDto.getSupplierId());
        welfareGoods.setBrandId(welfareGoodsManageAddDto.getBrandId());
        welfareGoods.setGoodsType(welfareGoodsManageAddDto.getGoodsType());
        welfareGoods.setFirstClassifyId(welfareGoodsManageAddDto.getFirstClassifyId());
        welfareGoods.setSecondClassifyId(welfareGoodsManageAddDto.getSecondClassifyId());
        welfareGoods.setThirdClassifyId(welfareGoodsManageAddDto.getThirdClassifyId());
        welfareGoods.setGoodsDetail(welfareGoodsManageAddDto.getGoodsDetail());
        welfareGoods.setGoodsImg(welfareGoodsManageAddDto.getGoodsImg());
        // 购买须知，购买须知开关
        welfareGoods.setBuyRemark(welfareGoodsManageAddDto.getBuyRemark());
        welfareGoods.setBuyRemarkSwitch(welfareGoodsManageAddDto.getBuyRemarkSwitch());

        // 设置规格组Json值
        if (EmptyUtils.isNotEmpty(welfareGoodsManageAddDto.getGoodsGroupList())) {
            welfareGoods.setGoodsGroupList(welfareGoodsManageAddDto.getGoodsGroupList());
        }
        // 商品类型
        if (EmptyUtils.isEmpty(welfareGoodsManageAddDto.getIsJicai()) && !welfareGoodsManageAddDto.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getCode()) && !welfareGoodsManageAddDto.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_PHYSICAL.getCode())) {
            resMap.put("code", 1914);
            resMap.put("msg", "无效的商品类型");
            return true;
        }
        if (welfareGoodsManageAddDto.getGoodsName().contains("<nb/>") || welfareGoodsManageAddDto.getGoodsName().contains("<br/>")) {
            resMap.put("code", 1901);
            resMap.put("msg", "非法的商品名");
            return true;
        }

        // 如果是虚拟商品，考虑购买限制类型和购买限制数量
        if (welfareGoodsManageAddDto.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getCode())) {
            if (EmptyUtils.isNotEmpty(welfareGoodsManageAddDto.getBuyLimitType())) {
                welfareGoods.setBuyLimitType(welfareGoodsManageAddDto.getBuyLimitType());
            }

            if (welfareGoodsManageAddDto.getBuyLimit() == null) {
                resMap.put("code", 1915);
                resMap.put("msg", "请填写购买限制（虚拟商品）");
                return true;
            } else {
                if (welfareGoodsManageAddDto.getBuyLimit().equals(0)) {
                    welfareGoods.setBuyLimit(GOODS_BUY_LIMIT);
                } else {
                    welfareGoods.setBuyLimit(welfareGoodsManageAddDto.getBuyLimit());
                }
            }
        }
        return false;
    }

    @Override
    public List<WelfareGoods> selectRelateGoodsNameByGroupId(Integer voucherGroupId) {
        return welfareGoodsMapper.selectRelateGoodsNameByGroupId(voucherGroupId);
    }

    @Override
    public List<SearchGoodsListVo> queryGoodsListByMiddleground(SearchGoodsQuery query) {
        List<SearchGoodsListVo> list = welfareGoodsMapper.queryGoodsListByMiddleground(query);
        if (EmptyUtils.isNotEmpty(list)) {
            list.forEach(x -> {
                if (EmptyUtils.isNotEmpty(x.getMinPrice()) && EmptyUtils.isNotEmpty(x.getMaxPrice())) {
                    if (x.getMinPrice().compareTo(x.getMaxPrice()) == 0) {
                        x.setGoodsPrice(x.getMinPrice().toString());
                    } else {
                        x.setGoodsPrice(x.getMinPrice() + "-" + x.getMaxPrice());
                    }
                } else {
                    x.setGoodsPrice("-");
                }
            });
        }
        return list;
    }

    @Override
    public Integer updateGoodsHide(String goodsIds, Integer isShow) {
        return welfareGoodsMapper.updateGoodsHide(goodsIds, isShow);
    }

    @Override
    public Integer updateGoodsSyncNonSelfSupportStatus(Integer platformId,Integer syncNonSelfSupport) {
        return welfareGoodsMapper.updateGoodsSyncNonSelfSupportStatus(platformId, syncNonSelfSupport);
    }

    @Override
    public Integer updateGoodsAttrCostPrice(List<WelfareGoodsAttrCostPriceDto> list) {
        list.forEach(x -> {
            WelfareGoodsAttr welfareGoodsAttr = new WelfareGoodsAttr();
            welfareGoodsAttr.setId(x.getId());
            welfareGoodsAttr.setCostPrice(x.getCostPrice());
            welfareGoodsAttrService.updateByPrimaryKeySelective(welfareGoodsAttr);
        });
        return list.size();
    }

    /*@Override
    public WelfareSupplier getSupplierByGoodsId(Integer goodsId) {
        return welfareGoodsMapper.getSupplierByGoodsId(goodsId);
    }*/
}